Friday, September 19, 2014

[Leetcode] 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?
Analysis:
左右子树为空,或者是最后访问的子树是当前子树的左或者右子树时,当前节点就可以访问了


/**
 * 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) {
        vector<int> ret;
        if (root == NULL)
            return ret;
        stack<TreeNode *> s;
        s.push(root);
        TreeNode * lastVisited = NULL;
        while(!s.empty())
        {
            TreeNode* curr = s.top();
            s.pop();
            if ((curr->left == NULL && curr->right == NULL) || 
                (curr->right != NULL && curr->right== lastVisited) ||
                (curr->right == NULL && curr->left == lastVisited))
            {
                lastVisited = curr;
                ret.push_back(curr->val);
            }
            else
            {
                s.push(curr);
                if (curr->right != NULL)
                    s.push(curr->right);
                if (curr->left != NULL)
                    s.push(curr->left);
            }
        }
        
        return ret;
    }
};

No comments:

Post a Comment