108. Convert Sorted Array to Binary Search Tree java solutions
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
1 /** 2 * Definition for a binary tree node. 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[] nums) { 12 return BST(nums,0,nums.length-1); 13 } 14 15 public TreeNode BST(int[] num,int low, int high){ 16 if(low > high) return null; 17 int mid = (low + high)/2; 18 TreeNode node = new TreeNode(num[mid]); 19 node.left = BST(num,low,mid-1); 20 node.right = BST(num,mid+1,high); 21 return node; 22 } 23 }
因为数组已经是有序的了,因此使用递归进行处理即可。