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.

 

 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         if (num==null || num.length==0) {
13             return null;
14         }
15       int middle = num.length/2;  
16       int[] firstarray= new int[middle];
17       int[] secondarray = new int[num.length-1-middle];
18       for (int i = 0; i < middle; i++) {
19         firstarray[i]=num[i];
20     }
21       for (int i = 0; i <secondarray.length; i++) {
22         secondarray[i]=num[middle+1+i];
23     }
24       TreeNode rootNode=new TreeNode(num[middle]);
25       rootNode.left=sortedArrayToBST(firstarray);
26       rootNode.right=sortedArrayToBST(secondarray);
27       return rootNode;
28     }
29 }

 

posted @ 2014-09-26 11:28  birdhack  阅读(136)  评论(0编辑  收藏  举报