Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:mac苹果电脑怎么删照片 编辑:程序博客网 时间:2024/06/05 02:07
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
以前写traversal的时候其实是死记硬背。。。谁在前谁在后,遇到这个题才这要搞懂。youtube有个人一步步给画了。不贴了
假设树 pre order为 a b c d e f g, 那么 a为root. 如果他的inorder 为 b c d a e f g 那么 bcd为左,def为右,然后递归的对左右做同样的操作。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { return helper(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1); } TreeNode* helper(vector<int>& preorder, int pStart, int pEnd, vector<int>& inorder, int iStart, int iEnd){ if (pStart>pEnd) return NULL; if (pStart==pEnd) return new TreeNode(preorder[pStart]); int rootInd; for (int i=iStart; i<=iEnd; i++){ if (inorder[i]==preorder[pStart]){ rootInd=i; break; } } TreeNode* root=new TreeNode(preorder[pStart]); int leftLen=rootInd-iStart; root->left=helper(preorder, pStart+1, pStart+leftLen, inorder, iStart, rootInd-1); root->right=helper(preorder, pStart+leftLen+1, pEnd, inorder, rootInd+1, iEnd); return root; }};
0 0
- *(leetcode) Construct Binary Tree from Preorder and Inorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode][tree] Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal & Construct Binary Tree from Inorder and P
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 109: Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Java.File
- uva10870 Recurrences矩阵快速幂
- C++项目目录组织结构
- gpg修改
- word2010公式编辑器 格式设置
- Construct Binary Tree from Preorder and Inorder Traversal
- 基于Node.JS的六款开源内容管理和静态网站生成系统
- 随机生成验证码和算术逻辑运算的实现以及详细解释
- poj3421
- 【无中生有】---9---分布式缓存实现
- mnesia 简单查询
- 小型反渗透设备价格表
- AngularJS的应用(3)
- iphone课程五:你必须要知道的苹果iPad的UX设计18原则