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?
/**
* 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;
stack<TreeNode* > sta;
TreeNode* cur = root;
TreeNode* pre = 0;
while (0 != cur || !sta.empty())
{
if (0 != cur)
{
sta.push(cur);
cur = cur->left;
}
else if (!sta.empty())
{
TreeNode* tmp = sta.top();
if (0 == tmp->right || tmp->right == pre)
{
res.push_back(tmp->val);
sta.pop();
pre = tmp;
}
else
cur = tmp->right;
}
}
return res;
}
};
本文详细介绍了如何通过迭代方法实现二叉树的后序遍历,提供了与递归方法对比的算法实现,并解释了迭代方法在效率和内存使用上的优势。
312

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



