题目描述:
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;
}
};
本文介绍了一种不使用递归的迭代方法来实现二叉树的后序遍历。通过使用栈结构存储节点,巧妙地调整了节点的访问顺序,从而实现了后序遍历的迭代算法。
7166

被折叠的 条评论
为什么被折叠?



