-
Notifications
You must be signed in to change notification settings - Fork 0
108. Convert Sorted Array to Binary Search Tree
Jacky Zhang edited this page Aug 25, 2016
·
1 revision
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Tree类题目。
BST的特征是对于一个node而言,左子树都比node小,右子树都比node大。 因此首先确定root,在array的中间,设为mid。 root的左孩子为[0,mid-1]的中间,root的右孩子为[mid+1,nums.length-1]的中间。 这个过程可以用过recursion来完成。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null) return null;
return helper(nums, 0, nums.length-1);
}
private TreeNode helper(int[] nums, int start, int end) {
if(start > end) return null;
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, start, mid-1);
root.right = helper(nums, mid+1, end);
return root;
}
}