Leetcode Construct Binary Tree from Preorder and Inorder Traversal
2014-07-02 21:23
369 查看
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
此题目有两种解决思路:
1)递归解决(比较好想)按照手动模拟的思路即可
2)非递归解决,用stack模拟递归
递归解决
Note:
You may assume that duplicates do not exist in the tree.
此题目有两种解决思路:
1)递归解决(比较好想)按照手动模拟的思路即可
2)非递归解决,用stack模拟递归
class Solution { public: TreeNode *buildTree(vector<int>& preorder, int pre_left,int pre_right, vector<int>& inorder, int in_left, int in_right){ if(pre_left > pre_right || in_left > in_right) return NULL; TreeNode *root = new TreeNode(preorder[pre_left]); int index = in_left; for( ; index <= in_right; ++ index ) if(inorder[index] == preorder[pre_left]) break; int left_cnt = index-in_left; root->left = buildTree(preorder,pre_left+1,pre_left+left_cnt,inorder,in_left,index-1); root->right = buildTree(preorder,pre_left+left_cnt+1,pre_right, inorder, index+1,in_right); return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size() == 0) return NULL; else return buildTree(preorder,0,preorder.size()-1, inorder,0,inorder.size()-1); } };
递归解决
相关文章推荐
- [leetcode刷题系列]Construct Binary Tree from Preorder and Inorder Traversal
- functionclass[LeetCode]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】
- 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 78] 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, Solution
- 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
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal