Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
public class Solution { public TreeNode sortedArrayToBST(int[] num) { // Start typing your Java solution below // DO NOT write main() function if(num == null || num.length == 0){ return null;} int len = num.length; return sortedArray(num, 0 ,len-1); } public TreeNode sortedArray(int[] num, int low, int high){ if(low == high){ TreeNode root= new TreeNode(num[low]);//make a new treenode return root; } else if(low > high){ return null; } else{ int mid = low + (high- low) /2; TreeNode root = new TreeNode(num[mid]); root.left = sortedArray(num,low,mid-1); root.right = sortedArray(num,mid+1,high); return root; } } }
mistake: make a new treenode to have new TreeNode(val);