首页 > 编程语言 > 详细

把排序数组转换为高度最小的二叉搜索树convert-sorted-array-to-binary-search-tree-with-minimal-height

时间:2015-12-03 02:09:53      阅读:306      评论:0      收藏:0      [点我收藏+]

给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

样例

给出数组 [1,2,3,4,5,6,7], 返回

     4
   /     2     6
 / \    / 1   3  5   7
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */ 
12 public class Solution {
13     /**
14      * @param A: an integer array
15      * @return: a tree node
16      */
17     public TreeNode sortedArrayToBST(int[] A) {  
18         // write your code here
19         if(A.length ==0 )  return null;
20         return sortedToBST(A, 0, A.length-1);
21     }
22     public TreeNode sortedToBST(int[] A,int start,int end){
23         if (start > end)
24             return null;
25         int mid = (start+end)/2;
26         TreeNode root = new TreeNode(A[mid]);
27         root.left = sortedToBST(A,start,mid-1);
28         root.right  = sortedToBST(A,mid+1,end);
29         return root;
30     }
31 }

 

把排序数组转换为高度最小的二叉搜索树convert-sorted-array-to-binary-search-tree-with-minimal-height

原文:http://www.cnblogs.com/wangnanabuaa/p/5014886.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!