LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:黄金家族软件 编辑:程序博客网 时间:2024/05/24 00:58
这个是一道深度优先搜索的题目。
我们如何处理中序遍历和后序遍历的数组,使其能够表示成一颗二叉搜索树呢?
我是这样处理的。
首先,我们知道后序遍历的数组。从后到前是树根-子树根-子子树根,好了,有了这个递归的顺序我们就可以执行了。
首先取出树根节点,在中序遍历的数组中寻找这个节点所在的位置,那么这个位置的左侧就是左子树,右侧是右子树。
根据这个道理再递归求解就可以了。唯一需要注意的是开始和结束。我之前每一个栈就开一个vector存下当前子树集,结果就超内存了,于是就每次指定位置了。
和这个题很像的兄弟题目是,你只需要把后序遍历数组从后往前开始,变成从前往后遍历。
代码如下:
class Solution {public: TreeNode* DFS(vector<int>& inorder, vector<int>& postorder,int s_p,int e_p,int s_i,int e_i) { //cout<<s_i<<" "<<e_i<<endl; //cout<<s_p<<" "<<e_p<<endl; if(s_i==e_i||s_p==e_p)return NULL; TreeNode* head = new TreeNode(-1); if(e_i-s_i==1) { TreeNode* tmp = new TreeNode(-1); //cout<<s_i<<endl; tmp->val = inorder[s_i]; return tmp; } else { int index; for(int i=s_i;i<e_i;i++) if(inorder[i]==postorder[e_p-1]){index = i;break;} int len = index-s_i; head->val = postorder[e_p-1]; head->right = DFS(inorder,postorder,e_p-(e_i-len)+s_i,e_p-1,index+1,e_i); // cout<<"hahah"<<endl; head->left = DFS(inorder,postorder,s_p,len+s_p,s_i,s_i+len); } return head; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if(inorder.empty())return NULL; return DFS(inorder,postorder,0,postorder.size(),0,inorder.size()); }};
0 0
- LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal [106]
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode 106] Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode 106]Construct Binary Tree from Inorder and Postorder Traversal
- leetcode || 106、Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal - LeetCode 106
- LeetCode 106:Construct Binary Tree from Postorder and Inorder Traversal
- LeetCode---(106)Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode #106 Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 106: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
- 【LEETCODE】106-Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】【106】Construct Binary Tree from Inorder and Postorder Traversal
- excel转Android string资源脚本
- Thinking in Java——第十五章-泛型
- xwiki的搭建
- Ubuntu下安装libpcap
- POJ 2352 Stars
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- HDOJ 1411 校庆神秘建筑
- 一个测试工程师面试官的真实分享!个人超赞同!
- Rightmost Dight(知识点:快速幂+题目分析)HDU1061
- Scala偏函数、异常、Lazy值编码之编程进阶(5)
- Android学习WebView使用小结
- Trie(字典树):大LCP
- 数据库三范式
- poj 2653 Pick-up sticks(线段相交 + 队列优化)