题目描述:
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
迭代实现二叉树的后序遍历。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root==NULL) return result;
stack<TreeNode*> s;
s.push(root);
TreeNode* p=root->left;
while(!s.empty())
{
if(p!=NULL)
{
s.push(p);
p=p->left;
}
else
{
if(s.top()->right==NULL)
{
result.push_back(s.top()->val);
p=s.top()->right;
s.pop();
}
else
{
p=s.top()->right;
s.top()->right=NULL;
}
}
}
return result;
}
};