145 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?

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?

Solution

/**
 * Definition for a binary tree node.
 * 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> res;
        if ( root == NULL ) return res;
        stack<TreeNode*> s;
        s.push(root);
        while ( ! s.empty() ) {
            TreeNode *tnode = s.top();
            s.pop();
            res.push_back(tnode->val);
            if ( tnode->left != NULL ) s.push(tnode->left);
            if ( tnode->right != NULL ) s.push(tnode->right);
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

results matching ""

    No results matching ""