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 creatBST(int low,int high,int[] num) {
        if(low<=high) {
            int mid = (low+high)/2;
            TreeNode root = new TreeNode(num[mid]);
            root.left = creatBST(low,mid-1,num);
            root.right = creatBST(mid+1,high,num);
            return root;
        }
        else return null;
    }
    
    public TreeNode sortedArrayToBST(int[] num) {
        return creatBST(0,num.length-1,num);
    }
}

 

posted @ 2015-04-12 19:42  mrpod2g  阅读(92)  评论(0编辑  收藏  举报