Thursday, January 15, 2015

Convert Sorted Array to Binary Search Tree (LeetCode Tree)

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

Idea: Recursion. The middle of the array is the tree root. Then build the left subtree based on the left half of the array [0...mid-1]. The right subtree is the right half [mid+1...end].

Time: O(n) Space: O(lgn) (Each recursion only pushes half of the tree to the stack)

Code:
 public class Solution {  
   public TreeNode sortedArrayToBST(int[] num) {  
     return build(num,0,num.length-1);  
   }  
   public TreeNode build(int[] num,int start,int end)  
   {  
     if(start>end)  
       return null;  
     int mid=(start+end)/2;  
     TreeNode root=new TreeNode(num[mid]);  
     root.left=build(num,start,mid-1);  
     root.right=build(num,mid+1,end);  
     return root;  
   }  
 }  

No comments:

Post a Comment