I am working on "Convert Sorted Array to Binary Search Tree With Minimal Height", which asked:
Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.
I am not able to find why my recursive does not stop as I expected. It should stop when 7 passed, and will not print out 7 again. I also found a similar answer, it looks like used same strategy as mine, but it works fine. (I don't think my question is duplicate as those questions listed above, but I still want to thank you to link them for me. They gave me more idea to solve 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 run it, I got this.
My input
[1,2,3,4,5,6,7,8]
My output
{4,2,6,1,3,5,7,#,#,#,#,#,#,7,8}
Expected
{4,2,6,1,3,5,7,#,#,#,#,#,#,#,8}
Why does it have duplicate 7 at right side? As 7 has been used, it should be kicked out.
And I found my idea is similar with 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;
}