问题描述如下:
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?
问题链接cpp代码如下:
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
TreeNode *p=root,*r=NULL;
stack<TreeNode*> sta;
vector<int> ans;
while(p||!sta.empty()){
if(p){
sta.push(p);
p=p->left;
}else{
p=sta.top();
if(p->right&&p->right!=r){
sta.push(p->right);
p=p->right->left;
}else{
ans.push_back(p->val);
sta.pop();
r=p;
p=NULL;
}
}
}
return ans;
}
};