forked from carpeventus/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReConstructTree.java
More file actions
55 lines (50 loc) · 2.09 KB
/
Copy pathReConstructTree.java
File metadata and controls
55 lines (50 loc) · 2.09 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package Chap2;
/**
* 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
* 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
*/
public class ReConstructTree {
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
/**
* 递归!
* [preStart + 1, preStart + i - inStart]是前序序列中左子树封闭区间
* [preStart + i - inStart + 1, preEnd]是前序序列中右子树封闭区间
*
* [inStart, i - 1]是中序序列中左子树封闭区间
* [i + 1, inEnd]是中序序列中右子树封闭区间
*
* @param pre 前序序列
* @param preStart 前序序列封闭区间的左指针
* @param preEnd 前序序列封闭区间的右指针
* @param in 中序序列
* @param inStart 中序序列封闭区间的左指针
* @param inEnd 中序序列封闭区间的右指针
* @return 树的根结点
*/
private TreeNode reConstructBinaryTree(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd) {
// 还有子数组就继续递归,不存在子数组了(表现为end > start),就返回空子树给父结点
if (preStart > preEnd || inStart > inEnd) {
return null;
}
int rootVal = pre[preStart];
TreeNode root = new TreeNode(rootVal);
for (int i = inStart; i <= inEnd; i++) {
if (in[i] == rootVal) {
root.left = reConstructBinaryTree(pre, preStart + 1, preStart + i - inStart, in, inStart, i - 1);
root.right = reConstructBinaryTree(pre, preStart + i - inStart + 1, preEnd, in, i + 1, inEnd);
}
}
return root;
}
}