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;
}
};
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;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解