题目:
Given an array where elements are sorted in ascending order, convert it to 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 }