105. 从前序与中序遍历序列构造二叉树

从前序与中序遍历序列构造二叉树

解法一: 分治

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func buildTree(preorder []int, inorder []int) *TreeNode {
n1 := len(preorder)
n2 := len(inorder)
inorderMap := make(map[int]int, n2)
for i, num := range inorder {
inorderMap[num] = i
}
return dfs(preorder, inorderMap, 0, n1-1, 0, n2-1)
}

func dfs(preorder []int, inorderMap map[int]int, preLeft, preRight, inLeft, inRight int) *TreeNode {
if preLeft > preRight {
return nil
}
node := &TreeNode{
Val: preorder[preLeft],
}
inMid := inorderMap[preorder[preLeft]]
preMid := preLeft + inMid - inLeft
node.Left = dfs(preorder, inorderMap, preLeft+1, preMid, inLeft, inMid-1)
node.Right = dfs(preorder, inorderMap, preMid+1, preRight, inMid+1, inRight)
return node
}
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n1 = preorder.length;
int n2 = inorder.length;
Map<Integer, Integer> inorderMap = new HashMap<Integer, Integer>(n2);
for (int i = 0; i < n2; i++) {
inorderMap.put(inorder[i], i);
}
return this.dfs(preorder, inorderMap, 0, n1 - 1, 0, n2 - 1);
}

private TreeNode dfs(int[] preorder, Map<Integer, Integer> inorderMap, int preLeft, int preRight, int inLeft, int inRight) {
if (preLeft > preRight) {
return null;
}
TreeNode node = new TreeNode(preorder[preLeft]);
int inMid = inorderMap.get(preorder[preLeft]);
int preMid = preLeft + inMid - inLeft;
node.left = this.dfs(preorder, inorderMap, preLeft + 1, preMid, inLeft, inMid - 1);
node.right = this.dfs(preorder, inorderMap, preMid + 1, preRight, inMid + 1, inRight);
return node;
}

}
作者

wuhunyu

发布于

2024-02-20

更新于

2025-01-15

许可协议