Thursday, January 23, 2014

[LeetCode] Binary Tree Postorder Traversal


/**
* 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;
        TreeNode* current;
        stack<TreeNode*> s;
        s.push(root);
        while(s.size()>0)
        {
            current = s.top();
            s.pop();
            if(current==NULL)
            {
                current = s.top();
                s.pop();
                ret.push_back(current->val);
                continue;
            }
            s.push(current);
            s.push(NULL);
            if(current->right)
                s.push(current->right);
            if(current->left)
                s.push(current->left);
        }
        return ret;
    }
};

No comments:

Post a Comment