[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.

https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

 

思路:递归实现,以中间节点作为根节点。

 

public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        return toBST(num,0,num.length);
    }
    private TreeNode toBST(int[] num, int from, int to){
        if(to-from<=0)
            return null;
        int mid=(from+to)/2;
        TreeNode root = new TreeNode(num[mid]);
        root.left=toBST(num,from,mid);
        root.right=toBST(num,mid+1,to);
        
        return root;
    }
}
View Code

 

第二遍记录:注意二分的时候边界问题 和 mid 溢出问题。

public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        return toBST(num,0,num.length-1);
    }
    
    private TreeNode toBST(int[]num, int from, int to){
        if(from>to){
            return null;
        }
        int mid = (to-from)/2+from;
        TreeNode root = new TreeNode(num[mid]);
        root.left=toBST(num,from,mid-1);
        root.right=toBST(num,mid+1,to);
        return root;
    }
    
}

 

第三遍记录:

类似二分查找,注意边界检查。

 

参考:

http://blog.csdn.net/xshengh/article/details/12705769

posted @ 2014-07-02 23:40  jdflyfly  阅读(124)  评论(0编辑  收藏  举报