码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode]108. Convert Sorted Array to Binary Search Tree

时间:2017-10-29 14:36:54      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:def   efi   code   tco   blog   cti   private   二分   treenode   

 

 

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

 

思路:既然数组里的元素已经按升序排好序了,那么不难想到用二分法来做这道题。

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length==0)
            return null;
        TreeNode T;                                      
        return T = binary(nums,0,nums.length-1);
    }
    private TreeNode binary(int[] nums,int p,int r){
        TreeNode T = null;                  
        if (r-p>=0){
            int q = (p+r)/2;
            T = new TreeNode(nums[q]);
            T.left = binary(nums,p,q-1);
            T.right = binary(nums,q+1,r);
        }
        return T;
    }
}

 

 

[Leetcode]108. Convert Sorted Array to Binary Search Tree

标签:def   efi   code   tco   blog   cti   private   二分   treenode   

原文地址:http://www.cnblogs.com/David-Lin/p/7749880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!