Working on a program "to convert a sorted array to binary search tree".
How to get the value return from the node? It does not print what I want.
Here is my code :
public class ConvertToBinarySearchTree { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { this.val = x; } } public static TreeNode sortedArraytoBST(int[] nums) { if (nums.length == 0) return null; return constructTreeNodeFromArray(nums, 0, nums.length - 1); } public static TreeNode constructTreeNodeFromArray(int[] nums, int left, int right) { // checking the boundary if (left > right) return null; int midpoint = left + (right - left) / 2; // get the index of the root TreeNode node = new TreeNode(nums[midpoint]); node.left = constructTreeNodeFromArray(nums, left, midpoint - 1); node.right = constructTreeNodeFromArray(nums, midpoint + 1, right); return node; } public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5, 6 }; System.out.println(sortedArraytoBST(arr)); } }
My output :
ConvertToBinarySearchTree$TreeNode@6504e3b2