forked from algorithm019/algorithm019
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildTree.java
More file actions
33 lines (29 loc) · 847 Bytes
/
buildTree.java
File metadata and controls
33 lines (29 loc) · 847 Bytes
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
/**
* @author libingc
* @date 2020/11/23
*/
//从前序和中序序列构建二叉树
public class buildTree {
public TreeNode Solution(int[] preorder, int[] inorder) {
return buildTreeHelper(preorder, inorder, (long)Integer.MAX_VALUE + 1);
}
int pre = 0;
int in = 0;
private TreeNode buildTreeHelper(int[] preorder, int[] inorder, long stop) {
//terminator
if(pre == preorder.length){
return null;
}
if (inorder[in] == stop) {
in++;
return null;
}
//process
int root_val = preorder[pre++];
TreeNode root = new TreeNode(root_val);
//drill down
root.left = buildTreeHelper(preorder, inorder, root_val);
root.right = buildTreeHelper(preorder, inorder, stop);
return root;
}
}