Convert Sorted Array to Balanced Binary Search Tree
发布时间:2020-12-14 04:23:37 所属栏目:大数据 来源:网络整理
导读:题目: 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 = sortedA
题目: Given an array where elements are sorted in ascending order,convert it to a height ? 解答: 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,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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |