leetcode -- Convert Sorted Array to Binary Search Tree

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

[解题思路]

递归确定每棵树的根节点的值,这里根节点的值是二分搜索的中值

由于这里是有序数组,确定root的时间复杂度为O(1), 整个算法的时间复杂度为O(n),n为节点数目。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode sortedArrayToBST(int[] num) {
12         // Start typing your Java solution below
13         // DO NOT write main() function
14         return generate(num, 0, num.length - 1);    
15     }
16     
17     public TreeNode generate(int[] num, int start, int end){
18         if(start > end){
19             return null;
20         }
21         int mid = (end + start) / 2;
22         TreeNode root = new TreeNode(num[mid]);
23         root.left = generate(num, start, mid - 1);
24         root.right = generate(num, mid + 1, end);
25         return root;
26     }
27 }

 

posted @ 2013-08-19 11:21  feiling  阅读(230)  评论(0编辑  收藏  举报