Wednesday, November 7, 2012

[LeetCode] Convert sorted array to binary search tree

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

Java Code:
  
public TreeNode sortedArrayToBST(int[] num) {
        return sortedSubArrayToBST(num, 0, num.length-1);
    }
      
      public TreeNode sortedSubArrayToBST(int[] num, int begin, int end){
          if( begin > end) return null;
          int middle = (begin+end)/2;
          
          TreeNode root = new TreeNode(num[middle]);
          
          root.left = sortedSubArrayToBST(num, begin, middle-1);
          root.right = sortedSubArrayToBST(num, middle+1, end);
          
          return root;
    }

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thank you for the example, I have seen similar code structure to build this bst but it didn't work because it did not have the last two if statement. That was important.

    ReplyDelete