[leetcode]Convert Sorted Array to Binary Search Tree

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 }

 

posted on 2014-07-31 20:19  喵星人与汪星人  阅读(138)  评论(0编辑  收藏  举报