convert sorted array/list to a height balanced BST.

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

 

/**

* Definition for binary tree

* public class TreeNode {

* int val;

* TreeNode left;

* TreeNode right;

* TreeNode(int x) { val = x; }

* }

*/

public class Solution {

public TreeNode sortedArrayToBST(int[] num) {

// Start typing your Java solution below

// DO NOT write main() function

if(num==null)

return null;



int start = 0;

int end = num.length-1;



return sortedArrayToBST(num,start,end);

}



public TreeNode sortedArrayToBST(int[] num,int start,int end)

{

if(num==null)

return null;



while(start<=end)

{

int mid = start + (end-start)/2;

TreeNode n = new TreeNode(num[mid]);

n.left = sortedArrayToBST(num,start,mid-1);

n.right = sortedArrayToBST(num,mid+1,end);

return n;

}

return null;

}

}




 
   
 

你可能感兴趣的:(convert)