首页 > 其他 > 详细

108. Convert Sorted Array to Binary Search Tree

时间:2016-03-14 09:33:13      阅读:165      评论:0      收藏:0      [点我收藏+]

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

 

Subscribe to see which companies asked this question

Hide Tags
 Tree Depth-first Search
 

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return createTree(nums, 0, nums.length);
    }
    
    private TreeNode createTree(int[] nums, int from, int to)
    {
        if(from>=to)
            return null;
        int len = to - from;
        if(len==1)
            return new TreeNode(nums[from]);
        
        int rootIndexOffset = len%2==0 ? len/2 : (len-1)/2;
        int rootIndex = from + rootIndexOffset;
        TreeNode root = new TreeNode(nums[rootIndex]);
        root.left = createTree(nums, from, rootIndex);
        root.right = createTree(nums, rootIndex+1, to);

        return root;
    }
}

 

108. Convert Sorted Array to Binary Search Tree

原文:http://www.cnblogs.com/neweracoding/p/5274485.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!