您的位置:首页 > 其它

LeetCode Binary Tree Postorder Traversal(二叉树的后序遍历 非递归实现)

2014-04-06 07:53 573 查看
题目要求:

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]
.

用栈模拟递归过程, 后序要比其它两个遍历方式稍微复杂些, 要判断左右子节点都遍历后在访问根节点。

代码:

class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
stack<TreeNode*> st;
vector<int> ret;
if(root == NULL)
return ret;
TreeNode* cur = NULL;
TreeNode* pre = NULL;
st.push(root);
while(!st.empty())
{
cur = st.top();
if((cur->left == NULL && cur->right == NULL) ||
(pre != NULL && (cur->left == pre || cur->right == pre)))//如果是叶子节点或者是左右子孩子已经被访问过了,才能访问当前节点
{
ret.push_back(cur->val);
st.pop();
pre = cur;
}
else
{
if(cur->right != NULL)
st.push(cur->right);
if(cur->left != NULL)
st.push(cur->left);
}
}
return ret;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐