import java.util.ArrayList;
import java.util.Collection;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){val=x;}
}
public class SortedArrayToBalancedBST {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length==0) return null;
else return sortedArrayToBST(nums, 0, nums.length-1);
}
public TreeNode sortedArrayToBST(int[] nums, int left, int right){
ArrayList<TreeNode> list = New ArrayList<TreeNode>()
TreeNode root =null;
int mid=(right+left)/2;
if(right>=left){
root= new TreeNode(nums[mid]);
root.left=sortedArrayToBST(nums, left, mid-1);
root.right=sortedArrayToBST(nums, mid+1, right);
list.add(root);
//System.out.print(list);
}
if(left>right) return null;
return root;
}
public static void main(String[] args) {
int nums[]= {1,3,5,7,9};
SortedArrayToBalancedBST s = new SortedArrayToBalancedBST();
s.sortedArrayToBST(nums);
System.out.print(s.toString())
}
I would like create a balanced tree by using the code above. But java return me an error that told me:Cannot invoke add(TreeNode) on the array type int[], so what should I do, why I can't add int type value to an array? And also I wish the output looks like [5,3,7,1,null,null,9] if I'm right.
An array type doesn't have an add(...)
method. You must specify the index to which you are replacing the element (ie arr[0] = 1;
). Also, if your array will contain null values, consider using Integer[]
type instead of the primitive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.