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?

/**
 * 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> result;
        if (root == NULL)
        {
            return result;
        }

        TreeNode *p = root;
        stack<TreeNode*> buf;
        buf.push(root);

        while (!buf.empty())
        {
            TreeNode *top = buf.top();
            if (top->left == NULL && top->right == NULL)
            {
                p = top;
                result.push_back(top->val);
                buf.pop();
            }
            else if (top->left && top->right == NULL)
            {
                if (top->left == p)
                {
                    p = top;
                    result.push_back(top->val);
                    buf.pop();
                }
                else
                {
                    buf.push(top->left);
                }
            }
            else if (top->right && top->left == NULL)
            {
                if (top->right == p)
                {
                    p = top;
                    result.push_back(top->val);
                    buf.pop();
                }
                else
                {
                    buf.push(top->right);
                }
            }
            else
            {
                if (top->left == p)
                {
                    buf.push(top->right);
                }
                else if (top->right == p)
                {
                    p = top;
                    result.push_back(top->val);
                    buf.pop();
                }
                else
                {
                    buf.push(top->left);
                }
            }
        }

        return result;
    }
};


你可能感兴趣的:(Binary Tree Postorder Traversal)