So I am implementing a BST, and right now I am trying to add the items from a sorted array.
I have a recursive function Dup:
private BNode Dup(T[] arr, int start, int end) {
if (start > end) return null;
BNode sub_root = new BNode(arr[(int)Math.Ceiling((double)((start + end) / 2))]);
sub_root.Left = Dup(arr, start, (start + end) / 2 - 1);
sub_root.Right = Dup(arr, (start + end) / 2 + 1, end);
return sub_root;
}
But if I pass it in an array that looks like [1,1], it adds the 1 at position 0 of the array, and then doesnt add the 1 at position 0 in the left subtree, (because when we make the recursive call, start = 0, end = -1), and then puts the other 1 into the right subtree (which is wrong!).
This is the only case I can see that doesn’t work..
Any ideas how to fix it? (I think it is most likely a math error)
thanks!
Why not reuse the same split index? Something like: