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]
.
/**
* 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> res;
if (!root) return res;
stack<TreeNode *> s;
TreeNode *p = root;
s.push(p);
while (!s.empty()) {
TreeNode *cur = s.top();
if (cur->right==p || cur->left==p || (!cur->left && !cur->right)) {
s.pop();
res.push_back(cur->val);
p = cur;
} else {
if (cur->right) s.push(cur->right);
if (cur->left) s.push(cur->left);
}
}
return res;
}
};