Problem
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
Solution (Java)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] num) {
/*1. Set up recursion*/
return makeTree(num, 0, num.length - 1);
}
private TreeNode makeTree(int[] num, int left, int right) {
/*2. left as lowest# can't be greater than right*/
if (left > right) {
return null;
}
/*3. Set median# as node*/
int mid = (left + right) / 2;
TreeNode midNode = new TreeNode(num[mid]);
/*4. Set mid node's kids*/
midNode.left = makeTree(num, left, mid - 1);
midNode.right = makeTree(num, mid + 1, right);
/*5. Sends node back || Goes back to prev node*/
return midNode;
}
}
Solution (Javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function(nums) {
return helper(nums, 0, nums.length - 1);
};
var helper = function (nums, ll, rr) {
if (ll > rr) return null;
var mid = Math.ceil((ll + rr) / 2);
var root = new TreeNode(nums[mid]);
root.left = helper(nums, ll, mid - 1);
root.right = helper(nums, mid + 1, rr);
return root;
};
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).