Binary Tree Postorder Traversal
来源:互联网 发布:md5加密 java代码 编辑:程序博客网 时间:2024/06/08 02:03
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]
.
// RECURSIVE VERSION:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void postorderTraversalHelper(vector<int> & solution, TreeNode * node){
if (node!=NULL){
postorderTraversalHelper(solution, node->left);
postorderTraversalHelper(solution, node->right);
solution.push_back(node->val);
}
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> solution;
postorderTraversalHelper(solution, root);
return solution;
}
};
// ITERATIVE VERSION:
/**
* 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> solution;
if (!root) return solution;
stack<TreeNode *> mystack;
stack<TreeNode *> output;
mystack.push(root);
while (!mystack.empty()){
TreeNode * curr = mystack.top();
output.push(curr);
mystack.pop();
if (curr->left)
mystack.push(curr->left);
if (curr->right)
mystack.push(curr->right);
}
while (!output.empty()){
solution.push_back(output.top()->val);
output.pop();
}
return solution;
}
};
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Cocos2d-x 3.0正式版 HelloWorld分析
- 《Android Design》 4.4 中文版
- OpenStack performance相关分析
- QT creator 编程中常见问题记录
- Linux踢出其他正在SSH登陆用
- Binary Tree Postorder Traversal
- 活用UML-软件设计高手(深圳,2014-4-26~27)- 活动报道
- 关于软件测试用例生成技术相关研究总结
- 运算符重载
- loadrunner 监控tomcat的代码
- 警察与小偷的实现之一客户端与服务端通信
- HDU 4453 Looploop(SplayTree)
- Seajs 使用总结
- 深入分析Linux内核源码