108. Convert Sorted Array to Binary Search Tree
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
這題有個重要的關鍵要觀察到,就是每次要從中位數開始建立node,才可以確保整個tree是balanced
Find the middle, root is the middle. left subtree is left part of middle. right subtree is right part of middle.
之後就是找尋中位數,並從[start, mid-1]加入左子樹與從[mid+1, end]加入右子樹。重複至start > end,表示沒值可以放了回傳null
T: O(N)
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0) return null;
TreeNode root = helper(nums, 0, nums.length -1);
return root;
}
public TreeNode helper(int[] nums, int start, int end){
if(end < start) return null;
int mid = start + (end - start)/2;
TreeNode node = new TreeNode(nums[mid]);
node.right = helper(nums, mid+1, end);
node.left = helper(nums, start, mid-1);
return node;
}
}
Previous236. Lowest Common Ancestor of a Binary TreeNext109. Convert Sorted List to Binary Search Tree
Last updated
Was this helpful?