mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
Update solution 0105
This commit is contained in:
@ -16,7 +16,23 @@ type TreeNode = structures.TreeNode
|
||||
* }
|
||||
*/
|
||||
|
||||
// 解法一, 直接传入需要的 slice 范围作为输入, 可以避免申请对应 inorder 索引的内存, 内存使用(leetcode test case) 4.7MB -> 4.3MB.
|
||||
func buildTree(preorder []int, inorder []int) *TreeNode {
|
||||
if len(preorder) == 0 {
|
||||
return nil
|
||||
}
|
||||
root := &TreeNode{Val: preorder[0]}
|
||||
for pos, node := range inorder {
|
||||
if node == root.Val {
|
||||
root.Left = buildTree(preorder[1:pos+1], inorder[:pos])
|
||||
root.Right = buildTree(preorder[pos+1:], inorder[pos+1:])
|
||||
}
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
// 解法二
|
||||
func buildTree1(preorder []int, inorder []int) *TreeNode {
|
||||
inPos := make(map[int]int)
|
||||
for i := 0; i < len(inorder); i++ {
|
||||
inPos[inorder[i]] = i
|
||||
|
Reference in New Issue
Block a user