LeetCode 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].


Stack Problem, One example will make this question easy to tackle.

LeetCode 145. Binary Tree Postorder Traversal_第1张图片

In this example, the post-order sequence is: 4, 5, 2, 6, 31.  

The process will be.... We first push 1 onto stack, Get the top element, pop it off, then push the left and right child.....

vector<int> postorderTraversal(TreeNode* root) {
        if(!root) return {};
        vector<int> res;
        stack<TreeNode*> nodes;
        nodes.push(root);
        while(!nodes.empty()) {
            TreeNode* tmp = nodes.top();
            nodes.pop();
            res.push_back(tmp->val);
            if(tmp->left) nodes.push(tmp->left);
            if(tmp->right) nodes.push(tmp->right);
        }
        reverse(res.begin(), res.end());
        return res;
    }


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