-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path108. Convert Sorted Array to Binary Search Tree
31 lines (27 loc) · 1.23 KB
/
108. Convert Sorted Array to Binary Search Tree
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
class Solution {
public TreeNode sortedArrayToBST(int[] nums){
int l=0;
int r=nums.length-1;
return growTree(nums, l, r);
}
public static TreeNode growTree(int nums[], int l, int r){
if(l>r) return null;
int mid=(l+r)/2; //make the middle element our root
TreeNode root = new TreeNode(nums[mid]); //all subtrees accumulates in root
root.left = growTree(nums, l, mid-1); //smaller elements will happen to the left of mid, so bring r to mid-1
root.right = growTree(nums, mid+1, r); //larger element will happen to the right of mid, so bring l to mid+1
return root;
}
}
/*
LOGIC---
Since in a height balanced binary search tree, the height can at max differ by 1 between left nad right subtree.
Hence, it makes sense to make the mid element the root node.
Approach---
If the array is empty, return null.
Find the middle element of the array and create a new node with its value.
Recursively construct the left subtree using the left half of the array.
Recursively construct the right subtree using the right half of the array.
Set the left and right child of the node created in step 2 to the root of the left and right subtree respectively.
Return the root node.
*/