Array to BST
JavaView on GFG
Advertisement
Intuition
Convert sorted array to height-balanced BST. Recursively use middle element as root.
Algorithm
- 1mid = (lo + hi) / 2. root = arr[mid]. root.left = build(lo, mid-1). root.right = build(mid+1, hi).
Common Pitfalls
- •Same as LC 108. Middle element as root ensures balance.
Array to BST.java
Java
// Approach: Sort array, then recursively build BST by picking the middle element as root.
// This guarantees a height-balanced BST.
// Time: O(n log n) Space: O(n)
class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
class Solution {
public Node sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0)
return null;
return sortedArrayToBST(nums, 0, nums.length - 1);
}
private Node sortedArrayToBST(int[] nums, int start, int end) {
if (start > end)
return null;
int mid = start + (end - start) / 2;
Node node = new Node(nums[mid]);
node.left = sortedArrayToBST(nums, start, mid - 1);
node.right = sortedArrayToBST(nums, mid + 1, end);
return node;
}
}Advertisement
Was this solution helpful?