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

leetcode Convert Sorted Array to Binary Search Tree

时间:2014-09-26 13:49:58      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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 }

 

leetcode Convert Sorted Array to Binary Search Tree

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/birdhack/p/3994510.html

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