mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2026-03-13 10:02:05 +08:00
Update 0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.md
update a new answer for less memory cost.
This commit is contained in:
@@ -70,6 +70,21 @@ func buildPreIn2TreeDFS(pre []int, preStart int, preEnd int, inStart int, inPos
|
||||
return root
|
||||
}
|
||||
|
||||
// 解法 2, 直接传入需要的 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
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user