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

Convert Sorted Array to Binary Search Tree

时间:2017-08-17 23:33:04      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:bin   arc   balance   help   length   bst   order   lan   elements   

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

public TreeNode sortedArrayToBST(int[] num) {
    if (num.length == 0) {
        return null;
    }
    TreeNode head = helper(num, 0, num.length - 1);
    return head;
}

public TreeNode helper(int[] num, int low, int high) {
    if (low > high) { 
        return null;
    }
    int mid = (low + high) / 2;
    TreeNode node = new TreeNode(num[mid]);
    node.left = helper(num, low, mid - 1);
    node.right = helper(num, mid + 1, high);
    return node;
}

  

Convert Sorted Array to Binary Search Tree

标签:bin   arc   balance   help   length   bst   order   lan   elements   

原文地址:http://www.cnblogs.com/GodBug/p/7384875.html

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