首页 > 代码库 > leetcode Convert Sorted Array to Binary Search Tree
leetcode Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
1 /** 2 * Definition for binary tree 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[] num) {12 if (num==null || num.length==0) {13 return null;14 }15 int middle = num.length/2; 16 int[] firstarray= new int[middle];17 int[] secondarray = new int[num.length-1-middle];18 for (int i = 0; i < middle; i++) {19 firstarray[i]=num[i];20 }21 for (int i = 0; i <secondarray.length; i++) {22 secondarray[i]=num[middle+1+i];23 }24 TreeNode rootNode=new TreeNode(num[middle]);25 rootNode.left=sortedArrayToBST(firstarray);26 rootNode.right=sortedArrayToBST(secondarray);27 return rootNode;28 }29 }
leetcode Convert Sorted Array to Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。