I want to convert a red black BST to an array, but something went wrong and I cannot figure that out. Here is the code snippet I used for this:
public T[] toArray() {
T[] array = (T[]) Array.newInstance(clazz, count);
inOrder(root, array, 0);
return array;
}
private void inOrder(Node<T> node, T[] array, int i) {
if (node != null) {
inOrder(node.leftChild(), array, i);
array[i++] = node.data();
inOrder(node.rightChild(), array, i);
}
}
After entering numbers from 10 to 200 in ascending order, the result is as follows (I used a pre-order bypass to see if the tree remains balanced):
[80, 40, 20, 10, 30, 60, 50, 70, 120, 100, 90, 110, 140, 130, 160, 150, 170, 180]
But when I call the method toArray(), I get the following:
80 120 140 160 170 180 null null null null null null null null null null null null
What have I done wrong here?