145. Binary Tree Postorder Traversal
来源:互联网 发布:大数据的教育弊端 编辑:程序博客网 时间:2024/05/18 02:47
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 a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void postOrderTraversal(vector<int>& vi,TreeNode* root) { if(root->left) postOrderTraversal(vi,root->left); if(root->right) postOrderTraversal(vi,root->right); vi.push_back(root->val); return; } vector<int> postorderTraversal(TreeNode* root) { vector<int> vi; if(!root) return vi; postOrderTraversal(vi,root); return vi; }};
栈
pre-order traversal is root-left-right, and post order is left-right-root. modify the code for pre-order to make it root-right-left, and then reverse the output so that we can get left-right-root .
- Create an empty stack, Push root node to the stack.
Do following while stack is not empty.
2.1. pop an item from the stack and print it.
2.2. push the left child of popped item to stack.
2.3. push the right child of popped item to stack.
reverse the ouput.
/** * 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> vi; if(!root) return vi; stack<TreeNode*> st; st.push(root); while(!st.empty()) { TreeNode* cur_node=st.top(); st.pop(); vi.push_back(cur_node->val); if(cur_node->left) st.push(cur_node->left); if(cur_node->right) st.push(cur_node->right); } reverse(vi.begin(),vi.end()); return vi; }};
1 0
- 145.Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- hdu3639 Hawk-and-Chicken(Tarjan缩点+反图搜索)
- AndroidAnnotations(Code Diet)android快速开发框架
- Hadoop整合Hive之API封装及操作
- Mysql 日志
- Hibernate(三)
- 145. Binary Tree Postorder Traversal
- Mysql 性能优化
- PETS-ICVS Datasets 数据集
- UITabelView分组样式时如何调整组之间的间距
- 211. Add and Search Word - Data structure design【M】【91】
- Learning OpenCV: read video and add onTrackSlider
- 关于图像对比度【5】——局部自适应对比度调整
- hibernate处理懒加载异常的方法
- Codeforces Round #317 [AimFund Thanks-Round] (Div. 2)A Arrays