Saturday, January 10, 2015

LeetCode 108: Convert Sorted Array to Binary Search Tree

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) {
        int lo = 0, hi = num.length - 1;
        
        return buildTree(num, lo, hi);
    }
    
    private TreeNode buildTree(int[] a, int lo, int hi)
    {
        if (lo > hi)
            return null;
            
        int mid = lo + (hi - lo)/2;
            
        TreeNode root = new TreeNode(a[mid]);
        
        root.left = buildTree(a, lo, mid-1);
        root.right = buildTree(a, mid+1, hi);
        
        return root;
    }
}

No comments:

Post a Comment