LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:淘宝企业店铺查假货吗 编辑:程序博客网 时间:2024/05/20 02:24
思路:后序数组用来确定根节点的值和在数中的位置,中序数组用来确定左右子树的大小。代码细节参考了《剑指offer》一书中给的code,注意截断序列的时候不要分错。
class Solution {public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {TreeNode * root;int len = postorder.size();if(len < 1)return NULL;elseroot = constructTree(inorder.begin(),inorder.end()-1,postorder.begin(),postorder.end()-1);return root; }TreeNode * constructTree(vector<int>::iterator in_itbegin, vector<int>::iterator in_itend, vector<int>::iterator post_itbegin, vector<int>::iterator post_itend){int v = *post_itend;TreeNode * root = new TreeNode(v);vector<int>::iterator p;for(p=in_itbegin; p<= in_itend;p++)if(*p == v)break;int leftlengh = p - in_itbegin, right_lengh = in_itend - p;if(leftlengh>0)root->left = constructTree(in_itbegin,p-1,post_itbegin,post_itend-right_lengh-1);if(right_lengh>0)root->right = constructTree(p+1,in_itend,post_itend-right_lengh+1,post_itend-1);return root;}};
0 0
- *(leetcode) Construct Binary Tree from Inorder and Postorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode-Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode - Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- 排序算法
- AsyncQueryHandler
- 基于linux-2.6.35的class_create,device_create解析 (可自动生成设备文件)
- 网站群的概念
- runtime blog
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- JAVA NIO 简介(也谈BIO | NIO | AIO )
- xx实体.hbm.xml 配置文件的主键生成机制说明
- 布莱恩.迪森 的发言稿
- 新的开始
- 比较 CEILING 和 FLOOR
- android软键盘输入,windowSoftInputMode
- 编辑距离算法
- 报告称中国网络文化低俗化趋势明显 存监管“真空”