1. 程式人生 > >二叉樹的非遞迴統一遍歷形式

二叉樹的非遞迴統一遍歷形式

核心思想是: 有交集的區域性有序會導致全域性有序!!!

void preorderTraversalNew(TreeNode *root, vector<int> &path)
{
    stack< pair<TreeNode *, bool> > s;
    s.push(make_pair(root, false));
    bool visited;
    while(!s.empty())
    {
        root = s.top().first;
        visited = s.top().second;
s.pop(); if(root == NULL) continue; if(visited) { path.push_back(root->val); } else { s.push(make_pair(root->right, false)); s.push(make_pair(root->left, false)); s.push(make_pair
(root, true)); } } }
//更簡單的非遞迴中序遍歷
void inorderTraversalNew(TreeNode *root, vector<int> &path)
{
    stack< pair<TreeNode *, bool> > s;
    s.push(make_pair(root, false));
    bool visited;
    while(!s.empty())
    {
        root = s.top().first;
        visited =
s.top().second; s.pop(); if(root == NULL) continue; if(visited) { path.push_back(root->val); } else { s.push(make_pair(root->right, false)); s.push(make_pair(root, true)); s.push(make_pair(root->left, false)); } } }
//更簡單的非遞迴後序遍歷
void postorderTraversalNew(TreeNode *root, vector<int> &path)
{
    stack< pair<TreeNode *, bool> > s;
    s.push(make_pair(root, false));
    bool visited;
    while(!s.empty())
    {
        root = s.top().first;
        visited = s.top().second;
        s.pop();
        if(root == NULL)
            continue;
        if(visited)
        {
            path.push_back(root->val);
        }
        else
        {
            s.push(make_pair(root, true));
            s.push(make_pair(root->right, false));
            s.push(make_pair(root->left, false));
        }
    }
}

有想深入理解的,可以參見原部落格,原文部落格連結地址是: 更簡單的非遞迴遍歷