码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Binary Tree *-order Traversal' by Iteration

时间:2014-12-16 07:39:36      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   ar   io   color   os   sp   on   

Binary Tree *-order traversal by recursion is trivial. But their iteration version deserves a look:

Pre-Order

class Solution 
{
    vector<int> ret;

public:
    
    vector<int> preorderTraversal(TreeNode *p) 
    {
        if (!p) return ret;

        stack<TreeNode *> stk;
        stk.push(p);
        while (!stk.empty())
        {
            TreeNode *pTop = stk.top(); stk.pop();

            ret.push_back(pTop->val);
            
            if (pTop->right) stk.push(pTop->right);
            if (pTop->left) stk.push(pTop->left);
        }
        return ret;
    }
};

In-Order

class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) 
    {
        vector<int> ret;
        if (!root) return ret;
        
        unordered_set<TreeNode*> bk;
        stack<TreeNode *> stk;
        stk.push(root);
        
        while (!stk.empty())
        {
            TreeNode *p = stk.top();
            if (p->left && bk.find(p->left) == bk.end())
            {
                stk.push(p->left);
                continue;
            }
            ret.emplace_back(p->val);
            stk.pop();
            bk.insert(p);            
            
            if (p->right)
            {
                stk.push(p->right);
            }
        }

        return ret;
    }
};

Post-Order - DIFFICULT

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) 
    {
        vector<int> ret;
        if (!root) return ret;
        
        //    Init
        stack<TreeNode *> stk;
        stk.push(root);
        TreeNode *pPre = nullptr;
        
        //    Go
        while (!stk.empty())
        {
            TreeNode *pCurr = stk.top(); 
            //    Down: from parent to child
            if (!pPre || pPre->left == pCurr || pPre->right == pCurr)
            {
                if (pCurr->left)
                    stk.push(pCurr->left);
                else if (pCurr->right)
                    stk.push(pCurr->right);
            }
            //    Up: from left child
            else if (pCurr->left == pPre)
            {
                if (pCurr->right)
                    stk.push(pCurr->right);
            }
            //    Up: from right child
            else
            {
                ret.push_back(pCurr->val);
                stk.pop();
            }
            pPre = pCurr;
        }
        return ret;
    }
};

LeetCode "Binary Tree *-order Traversal' by Iteration

标签:des   style   blog   ar   io   color   os   sp   on   

原文地址:http://www.cnblogs.com/tonix/p/4166262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!