给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1]
输出: [-1]
提示:
- 1 <= preorder.length <= 3000
- inorder.length == preorder.length
- -3000 <= preorder[i], inorder[i] <= 3000
- preorder 和 inorder 均 无重复 元素
- inorder 均出现在 preorder
- preorder 保证 为二叉树的前序遍历序列
- inorder 保证 为二叉树的中序遍历序列
解答:
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 {
return nil
}
var root = &TreeNode{}
res := root
var dfs func(inorder []int, node *TreeNode)
dfs = func(inorder []int, node *TreeNode) {
node.Val = preorder[0]
preorder = preorder[1:]
var left, right []int
for i := 0; i < len(inorder); i++ {
if inorder[i] == node.Val {
left = inorder[:i]
right = inorder[i+1:]
break
}
}
if len(left) > 0 && len(preorder) > 0 {
node.Left = &TreeNode{}
dfs(left, node.Left)
}
if len(right) > 0 && len(preorder) > 0 {
node.Right = &TreeNode{}
dfs(right, node.Right)
}
}
dfs(inorder, root)
return res
}
官方解答:
1.递归
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 {
return nil
}
root := &TreeNode{preorder[0], nil, nil}
i := 0
for ; i < len(inorder); i++ {
if inorder[i] == preorder[0] {
break
}
}
root.Left = buildTree(preorder[1:i+1], inorder[:i])
root.Right = buildTree(preorder[i+1:], inorder[i+1:])
return root
}
2.迭代
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 {
return nil
}
root := &TreeNode{preorder[0], nil, nil}
stack := []*TreeNode{root}
var inorderIndex int
for i := 1; i < len(preorder); i++ {
preorderVal := preorder[i]
node := stack[len(stack)-1]
if node.Val != inorder[inorderIndex] {
node.Left = &TreeNode{preorderVal, nil, nil}
stack = append(stack, node.Left)
} else {
for len(stack) != 0 && stack[len(stack)-1].Val == inorder[inorderIndex] {
node = stack[len(stack)-1]
stack = stack[:len(stack)-1]
inorderIndex++
}
node.Right = &TreeNode{preorderVal, nil, nil}
stack = append(stack, node.Right)
}
}
return root
}