您的位置:首页 > 编程语言 > C语言/C++

leetcode #145 in cpp

2016-06-26 12:06 309 查看
Solution:

The post-order is the reverse of the root->right->left order. The root->right->left order is similar to pre-order traversal. Thus we first do a pseudo-pre-order traversal, by collecting root first, then right node, then left node. As we collect all nodes
we reverse the collection. 

Code:

/**
* 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) {
stack<TreeNode*> stk1;
stack<TreeNode*> stk2;
if(root) stk1.push(root);
TreeNode*cur;
while(!stk1.empty()){
cur = stk1.top();
stk1.pop();
stk2.push(cur);
if(cur->left) stk1.push(cur->left);
if(cur->right) stk1.push(cur->right);

}
vector<int> res;
while(!stk2.empty()){
res.push_back(stk2.top()->val);
stk2.pop();
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode