您的位置:首页 > 其它

Binary Tree Postorder Traversal

2015-12-18 10:28 253 查看

Binary Tree Postorder Traversal

Total Accepted: 82814 Total Submissions: 244246 Difficulty: Hard

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?

(M) Binary Tree Inorder Traversal

/**
* Definition for a binary tree node.
* 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<pair<TreeNode*,bool>> paths;
TreeNode*                   p = root;

while(p || !paths.empty()){
while(p){
paths.push(make_pair(p,false));
p = p->left;
}
while(!paths.empty()){
pair<TreeNode*,bool>& node = paths.top();
if(node.second){
res.push_back(node.first->val);
paths.pop();
}else{
p = node.first->right;
node.second = true;
break;
}
}
}

return res;
}
};


Next challenges: (H) Binary Tree Maximum Path Sum (E) Implement Stack using Queues (M) Binary Tree Longest Consecutive Sequence
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: