leetcode#105 Construct Binary Tree from Preorder and Inorder Traversal
2017-03-28 18:54
573 查看
Desciption
Given preorder and inorder traversal of a tree, construct the binary tree.
这道题很简单,先序的第一个元素就是根元素,然后在中序中找到对应的位置,则左边的就是左子树,右边的即为右子树。值得注意的是,C++切片操作很难用,所以我就用Go写的解答。最后大部分debug时间都在解决语法问题T_T
Solution
Given preorder and inorder traversal of a tree, construct the binary tree.
这道题很简单,先序的第一个元素就是根元素,然后在中序中找到对应的位置,则左边的就是左子树,右边的即为右子树。值得注意的是,C++切片操作很难用,所以我就用Go写的解答。最后大部分debug时间都在解决语法问题T_T
Solution
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func buildTree(preorder []int, inorder []int) *TreeNode { if (len(preorder) == 0) { return nil } root := new(TreeNode) root.Val = preorder[0] var i int = 0 for; i < len(inorder); i++ { if inorder[i] == preorder[0] { break } } root.Left = buildTree(preorder[1: i+1], inorder[0: i]) root.Right = buildTree(preorder[i+1: len(preorder)], inorder[i+1: len(inorder)]) return root }
相关文章推荐
- leetcode[105]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 105: 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---(105)Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode 105, Medium] 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 [105]
- [Leetcode 78] 105 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
- [JAVA]LeetCode105 Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105/106 Construct Binary Tree from Preorder/Postorder and Inorder Traversal
- 【LeetCode-面试算法经典-Java实现】【105-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:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium
- [leetcode-105]Construct Binary Tree from Preorder and Inorder Traversal(java)