Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

 

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

递归版本就不写了,那个没难度。

迭代的方法,利用一个栈。左子树一律进栈。当没有左子树的情况出现时,再考虑又子树。

由于访问过的点可能也存在左子树和右子树,所以用一个last标记刚刚访问过的节点。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        stack<TreeNode*> sk;
        vector<int>re;
        if(root == NULL)return re;
        TreeNode *last=NULL;
        sk.push(root);
        while(root->left != NULL)
        {
            
            root = root->left;
            sk.push(root);
        }
        
        while(!sk.empty())
        {
            TreeNode *now = sk.top();
            if(now->right!= NULL &&now->right!=last)
            {
                now=now->right;
                sk.push(now);
            
                while(now->left != NULL){
                    sk.push(now->left);
                    now = now->left;
                    continue;
                }
            }
            else //(now->right ==NULL)
            {
                re.push_back(now->val);
                sk.pop();
                last = now;
            }
        }
        return re;
    }
};

  

posted on 2014-03-26 11:23  pengyu2003  阅读(107)  评论(0编辑  收藏  举报

导航