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

Convert Sorted Array to Binary Search Tree

时间:2016-08-16 21:30:32      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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

 1 /**
 2  * Definition for a binary tree node.
 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[] nums) {
12         if (nums == null) {
13             return null;
14         }
15         return builder(nums, 0, nums.length - 1);
16     }
17     
18     private TreeNode builder(int[] nums, int start, int end) {
19         if (start > end) {
20             return null;
21         }
22         int mid = start + (end - start) / 2;
23         TreeNode root = new TreeNode(nums[mid]);
24         TreeNode left = builder(nums, start, mid - 1);
25         TreeNode right = builder(nums, mid + 1, end);
26         root.left = left;
27         root.right = right;
28         return root;
29     }
30 }

 

Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5777696.html

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