【LeetCode-145】Binary Tree Postorder Traversal(C++)
来源:互联网 发布:网络应急演练总结 编辑:程序博客网 时间:2024/06/05 05:56
题目要求:完成二叉树的后序遍历(递归的方式很简单,请尝试用循环的方式来完成)
解决方法:
1.递归
/** * 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> v; if(root==NULL) return v; vector<int> vr=postorderTraversal(root->right); v=postorderTraversal(root->left); for(int i=0;i<vr.size();i++){ v.push_back(vr[i]); } v.push_back(root->val); return v; }};2. 后序遍历中那些具有右子节点的节点都要遍历两次,故需要用到两个栈,一个栈用来存储遍历过的节点,另一个栈用来存储相应节点的遍历次数(0代表遍历过一次,1代表遍历过第二次,在遍历过第二次的时候才能将节点值加入到数组中)。
/** * 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> v; if(root==NULL) return v; stack<TreeNode*> st; stack<int> vs; TreeNode* p=root; while(p){ st.push(p); vs.push(0); p=p->left; } while(!st.empty()){ p=st.top(); while(p->right&&vs.top()==0){ vs.pop(); vs.push(1); p=p->right; st.push(p); vs.push(0); while(p->left){ p=p->left; st.push(p); vs.push(0); } } p=st.top(); v.push_back(p->val); st.pop(); vs.pop(); } return v; }};
0 0
- [leetcode-145]Binary Tree Postorder Traversal(c++)
- 【LeetCode-145】Binary Tree Postorder Traversal(C++)
- #LeetCode# #C++# Binary Tree Postorder Traversal
- LeetCode(145)Binary Tree Postorder Traversal
- LeetCode: Binary Tree Postorder Traversal [145]
- LeetCode 145 Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode || 145、Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode 145
- Leetcode[145]-Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode(145):Binary Tree Postorder Traversal
- leetcode-145-Binary Tree Postorder Traversal
- [Leetcode 145, Hard] Binary Tree Postorder Traversal
- leetcode[145]:Binary Tree Postorder Traversal
- Leetcode #145 Binary Tree Postorder Traversal
- LeetCode 145 : Binary Tree Postorder Traversal
- LeetCode 145: Binary Tree Postorder Traversal
- C#中TransactionScope的使用方法和原理
- 结构体做函数参数
- poj 2345 Central Heating
- 微信公众号-写作主题
- 欢迎使用CSDN-markdown编辑器
- 【LeetCode-145】Binary Tree Postorder Traversal(C++)
- ActionBar结合Fragment实现Tab导航
- <Android 应用 之路> 百度地图API使用(4)
- # zookeeper 单机版server启动
- POJ 2828 线段树单点更新
- 求连续子数组的最大和
- CSS各种居中方法
- 替换空格 剑指offer 02
- android 刷机ROM结构与编译制作。