How to convert red black BST to an array?

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?

+4
source share
1 answer

, . i , .

, :

    80
   /  \
  40  120

3.

:

  • i - 0.
  • inOrder :
    • i - 0.
    • inOrder , null.
    • 40 0, i 1.
    • inOrder , null.
    • .
  • i 0!
  • 80 0, i 1.
  • inOrder :
    • i - 1.
    • inOrder , null.
    • 120 1, i 2.
    • inOrder , null.
    • .
  • .

[80, 120, null].

return i , i .

private int inOrder(Node<T> node, T[] array, int i) {
    if (node != null) {
        i = inOrder(node.leftChild(), array, i);
        array[i++] = node.data();
        i = inOrder(node.rightChild(), array, i);
    }
    return i;
}
+6

All Articles