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?
后序遍历,不能使用递归
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> rel;
if(root==NULL) return rel;
s.push(*root);
while(!s.empty()) {
TreeNode & v = s.top();
if(v.right==NULL && v.left==NULL) {
rel.push_back(v.val);
s.pop();
} else {
if(v.right!=NULL) {
s.push(*v.right);
v.right = NULL;
}
if(v.left!=NULL) {
s.push(*v.left);
v.left = NULL;
};
}
}
return rel;
}
stack<TreeNode> s;
};