Convert Sorted Array to Balanced Binary Search Tree
Posted wylwyl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Convert Sorted Array to Balanced Binary Search Tree相关的知识,希望对你有一定的参考价值。
题目:
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的主要内容,如果未能解决你的问题,请参考以下文章
108. Convert Sorted Array to Binary Search Tree
Convert Sorted Array to Binary Search Tree
leetcode 108 Convert Sorted Array to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree