I am working on "Convert a sorted array to a binary search tree with a minimum height", which asked:
Given a sorted array (order of magnification), convert it to create a binary tree with a minimum height.
I cannot find why my recursiveness does not stop as I expected. He should stop when 7 passes, and will not print 7 again. I also found a similar answer, it looks the same as mine, but it works fine. (I donβt think my question repeats itself, as these questions are listed above, but I still want to thank you to connect them for me. They gave me more ideas for solving my problem.)
My code is below:
public TreeNode sortedArrayToBST(int[] A) { int len = A.length; if(len <= 0){ return null; } TreeNode root = new TreeNode(A[(len - 1) / 2]); if(len == 1){ return root; } else{ helper(root, A, 0, len - 1); } return root; } public void helper(TreeNode root, int[] A, int leftPoint, int rightPoint){ if((rightPoint - leftPoint) <= 0){ return; } int mid = (rightPoint - leftPoint) / 2 + leftPoint; int leftChild = (mid - 1 - leftPoint) / 2 + leftPoint; int rightChild = (rightPoint - (mid + 1)) / 2 + mid + 1; TreeNode left = new TreeNode(A[leftChild]); root.left = left; TreeNode right = new TreeNode(A[rightChild]); root.right = right; helper(root.left, A, leftPoint, mid - 1); helper(root.right, A, mid + 1, rightPoint); return; }
When I launched it, I got this.
My details
[1,2,3,4,5,6,7,8]
My conclusion
{4,2,6,1,3,5,7,#,#,#,#,#,#,7,8}
Expected
{4,2,6,1,3,5,7,#,#,#,#,#,#,#,8}
Why does he have duplicate 7 on the right side? Since 7 was used, it should be kicked out.
And I realized that my idea is similar to the following answer:
public TreeNode sortedArrayToBST(int[] A) { // write your code here int len = A.length; if(len <= 0){ return null; } TreeNode root = helper1(A, 0, len - 1); return root; } public TreeNode helper1(int[] A, int low, int high){ if(low > high){ return null; } int mid = (high + low) / 2; TreeNode root = new TreeNode(A[mid]); root.left = helper1(A, low, mid - 1); root.right = helper1(A, mid + 1, high); return root; }