Skip to content

Commit 6df650d

Browse files
Create 106. 从中序与后序遍历序列构造二叉树.md
1 parent cc1f257 commit 6df650d

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#### 106. 从中序与后序遍历序列构造二叉树
2+
3+
难度:中等
4+
5+
---
6+
7+
给定两个整数数组 `inorder``postorder` ,其中 `inorder` 是二叉树的中序遍历, `postorder` 是同一棵树的后序遍历,请你构造并返回这颗 _二叉树_ 。
8+
9+
**示例 1:**
10+
11+
![](https://assets.leetcode.com/uploads/2021/02/19/tree.jpg)
12+
```
13+
输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
14+
输出:[3,9,20,null,null,15,7]
15+
```
16+
17+
**示例 2:**
18+
19+
```
20+
输入:inorder = [-1], postorder = [-1]
21+
输出:[-1]
22+
```
23+
24+
**提示:**
25+
26+
* `1 <= inorder.length <= 3000`
27+
* `postorder.length == inorder.length`
28+
* `-3000 <= inorder[i], postorder[i] <= 3000`
29+
* `inorder` 和 `postorder` 都由 **不同** 的值组成
30+
* `postorder` 中每一个值都在 `inorder` 中
31+
* `inorder`  **保证** 是树的中序遍历
32+
* `postorder`  **保证** 是树的后序遍历
33+
34+
---
35+
36+
深度搜索优先:
37+
38+
每次递归对中序序列和后序序列做切片。具体切到什么位置,拿示例推理一遍。
39+
40+
```Go
41+
/**
42+
* Definition for a binary tree node.
43+
* type TreeNode struct {
44+
* Val int
45+
* Left *TreeNode
46+
* Right *TreeNode
47+
* }
48+
*/
49+
func buildTree(inorder []int, postorder []int) *TreeNode {
50+
end := len(postorder) - 1
51+
for i := range inorder {
52+
if inorder[i] == postorder[end] {
53+
return &TreeNode {
54+
Val: inorder[i],
55+
Left: buildTree(inorder[:i], postorder[:i]),
56+
Right: buildTree(inorder[i+1:], postorder[i:end]),
57+
}
58+
}
59+
}
60+
return nil
61+
}
62+
```

0 commit comments

Comments
 (0)