Convert Sorted Array to Binary Search Tree

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

Convert Sorted Array to Binary Search Tree
 1 public class Solution {
 2     public TreeNode sortedArrayToBST(int[] num) {
 3         if(num.length==0) return null;
 4         return get(num,0,num.length-1);
 5     }
 6     public TreeNode get(int []num,int start,int end){
 7         if(start>end) return null;
 8         int mid = (start+end)/2;
 9         TreeNode p = new TreeNode (num[mid]);
10         p.left = get(num,start,mid-1);
11         p.right = get(num,mid+1,end);
12         return p;
13     }
14    
15 }
View Code

 

 

Convert Sorted Array to Binary Search Tree

上一篇:2月6日:linux下命令与查看方式


下一篇:Search in Rotated Sorted Array