Skip to content

Commit 5f38168

Browse files
authored
Merge pull request #131 from qilingit/day24
Add Java solution for day24: Construct Binary Search Tree from Preorder Traversal
2 parents 368b00e + b188974 commit 5f38168

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
/**
18+
* Recursive solution, construct the left tree and right tree recursively, and the combine to the root.
19+
* @param preorder
20+
* @return
21+
*/
22+
public TreeNode bstFromPreorder(int[] preorder) {
23+
if(preorder.length == 0) return null;
24+
25+
int rootVal = preorder[0];
26+
if(preorder.length == 1) return new TreeNode(rootVal);
27+
28+
TreeNode rightTree = null;
29+
TreeNode leftTree = null;
30+
TreeNode root = new TreeNode(rootVal, null, null);
31+
32+
if(preorder[1] > rootVal) {
33+
// if there is no left tree
34+
rightTree = bstFromPreorder(Arrays.copyOfRange(preorder, 1, preorder.length));
35+
} else {
36+
int i = 1;
37+
while (i < preorder.length) {
38+
// find separate index of left tree and right tree
39+
if (preorder[i] > rootVal) {
40+
break;
41+
}
42+
i++;
43+
}
44+
45+
// construct left tree
46+
leftTree = bstFromPreorder(Arrays.copyOfRange(preorder, 1, i));
47+
if(i != preorder.length) {
48+
//construct right tree
49+
rightTree = bstFromPreorder(Arrays.copyOfRange(preorder, i, preorder.length));
50+
}
51+
}
52+
53+
root.left = leftTree;
54+
root.right = rightTree;
55+
56+
return root;
57+
}
58+
}

0 commit comments

Comments
 (0)