Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0){
return null;
}
return getTreeNode(nums, 0, nums.length -1);
}
private TreeNode getTreeNode( int[] nums, int a , int b){
int start = a;
int end = b ;
if(start > end){
return null;
}
int mid = (start +end) / 2 ;
TreeNode node = new TreeNode(nums[mid]);
node.left = getTreeNode(nums, start , mid -1);
node.right = getTreeNode(nums, mid+1 , end);
return node;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0){
return null;
}
return getTreeNode(nums, 0, nums.length -1);
}
private TreeNode getTreeNode( int[] nums, int a , int b){
int start = a;
int end = b ;
if(start > end){
return null;
}
int mid = (start +end) / 2 ;
TreeNode node = new TreeNode(nums[mid]);
node.left = getTreeNode(nums, start , mid -1);
node.right = getTreeNode(nums, mid+1 , end);
return node;
}
}
No comments:
Post a Comment