Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
2013-01-13 12:19
639 查看
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if(preorder.size()==0||preorder.size()!=inorder.size()) return NULL; map<int,int> mapper; for(int i=0;i<inorder.size();++i) mapper[inorder[i]]=i; return helper(preorder,inorder,mapper,0,0,preorder.size()-1); } TreeNode* helper(vector<int>& preorder,vector<int>& inorder,map<int,int>& mapper,int root,int start,int end){ if(start>end) return NULL; int r=preorder[root]; int index=mapper[r]; TreeNode* node= new TreeNode(r); node->left=helper(preorder,inorder,mapper,root+1,start,index-1); node->right=helper(preorder,inorder,mapper,root+index-start+1,index+1,end); return node; } };
相关文章推荐
- [leetcode] 105.Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode105 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 || 105、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】【Medium】Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] #105 Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode 105. 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 LeetCode 105
- LeetCode_Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal