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

Convert Sorted Array to Balanced Binary Search Tree

时间:2019-02-22 16:44:55      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:bsp   EDA   nbsp   alt   sorted   oid   style   asc   string   

题目:

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

技术图片

 

解答:

 1 public class Solution {
 2 
 3     public static void main(String[] args) {
 4         int[] num = {1,2,3,4,5};
 5 
 6         TreeNode root = sortedArrayToBST(num);
 7 
 8         InOrder(root);
 9 
10     }
11 
12     public static TreeNode sortedArrayToBST(int[] num) {
13         return sortedArrayToBST(num, 0, num.length-1);
14     }
15 
16     private static sortedArrayToBST(int[] arr, int start, int end) {
17         if(start > end) {
18             return null;
19         }
20 
21         int mid = (start + end) >> 1;
22         TreeNode node = new TreeNode(arr[mid]);
23         node.left = sortedArrayToBST(arr, start, mid-1);
24         node.right = sortedArrayToBST(arr, mid+1, end);
25         return node;
26     }
27 
28     public static void InOrder(TreeNode root) {
29 
30         if(root == null) {
31             return;
32         }
33 
34         if(root.left != null) {
35             InOrder(root.left);
36         }
37 
38         System.out.println(root.val);
39 
40         if(root.right != null) {
41             InOrder(root.right);
42         }
43 
44     }
45 }

技术图片

 

Convert Sorted Array to Balanced Binary Search Tree

标签:bsp   EDA   nbsp   alt   sorted   oid   style   asc   string   

原文地址:https://www.cnblogs.com/wylwyl/p/10419085.html

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