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

[leetcode]Convert Sorted Array to Binary Search Tree

时间:2014-07-31 23:20:00      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   代码   div   

Convert Sorted Array to Binary Search Tree

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

算法:根据有序数组,生成BST,递归实现。

代码如下:

 1 public class Solution {
 2     public TreeNode sortedArrayToBST(int[] num) {
 3           if(num == null || num.length == 0) return null;
 4           int mid = num.length >> 1;
 5           TreeNode node = new TreeNode(num[mid]);
 6           int[] left = Arrays.copyOfRange(num, 0, mid);
 7           int[] right = Arrays.copyOfRange(num, mid + 1, num.length);
 8           node.left = sortedArrayToBST(left);
 9           node.right = sortedArrayToBST(right);
10           return node;
11      
12     }
13 }

 

[leetcode]Convert Sorted Array to Binary Search Tree,布布扣,bubuko.com

[leetcode]Convert Sorted Array to Binary Search Tree

标签:style   blog   http   color   io   ar   代码   div   

原文地址:http://www.cnblogs.com/huntfor/p/3883527.html

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