-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array to BST
39 lines (33 loc) · 1.05 KB
/
Array to BST
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
class Solution {
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
this.left = this.right = null;
}
}
public int[] sortedArrayToBST(int[] nums) {
Node root = sortedArrayToBSTUtil(nums, 0, nums.length - 1);
int[] index = new int[] {0};
preOrder(root, nums, index);
return nums;
}
private Node sortedArrayToBSTUtil(int[] nums, int start, int end) {
if(start > end)
return null;
int mid = start + (end - start) / 2;
Node root = new Node(nums[mid]);
root.left = sortedArrayToBSTUtil(nums, start, mid - 1);
root.right = sortedArrayToBSTUtil(nums, mid + 1, end);
return root;
}
private void preOrder(Node root, int[] nums, int[] index) {
if(root == null)
return;
nums[index[0]++] = root.data;
preOrder(root.left, nums, index);
preOrder(root.right, nums, index);
}
}