Files
interview/16-LeetCode Hot 100/从前序与中序遍历序列构造二叉树.md

42 lines
987 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 从前序与中序遍历序列构造二叉树
## 题目描述
给定两个整数数组 preorder 和 inorder其中 preorder 是二叉树的先序遍历inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
## 解题思路
### 递归构造
前序遍历:[根, [左子树], [右子树]]
中序遍历:[[左子树], 根, [右子树]]
## 解法
```go
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 {
return nil
}
root := &TreeNode{Val: preorder[0]}
index := findIndex(inorder, preorder[0])
root.Left = buildTree(preorder[1:1+index], inorder[:index])
root.Right = buildTree(preorder[1+index:], inorder[index+1:])
return root
}
func findIndex(arr []int, target int) int {
for i, v := range arr {
if v == target {
return i
}
}
return -1
}
```
**复杂度:** O(n²) 时间(可用哈希表优化到 O(n)O(n) 空间