您的位置:首页 > 其它

Binary Tree Postorder Traversal

2015-09-08 16:55 169 查看
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> path;
if(root==NULL)return path;
stack<TreeNode*> stk;
stk.push(root);//将根节点入栈
TreeNode* cur = NULL;
while(!stk.empty())//如果栈非空
{
cur = stk.top();//将cur指向当前栈首。
//如果左右子树为空,
if(cur->left ==NULL && cur->right ==NULL)
{
path.push_back(cur->val);//如果左右子树都处理过,就表示栈为空
stk.pop();
}else{
if(cur->right)//如果存在右子树,这里先右子树入栈。
{
stk.push(cur->right);
cur->right = NULL;//表示根节点右子树处理
}
if(cur->left)//如果存在左子树。
{
stk.push(cur->left);
cur->left = NULL;//表示跟节点左子树处理过
}
}
}
return path;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: