In-order Traversal: Recursive Implementation

  • Implement in-order traversal.

For BST implementation of OrderedSet ADT, we must iterate over the nodes using in-order traversal, so the outcome is "ordered" (sorted).

We will try to implement a recursive in-order traversal first before implementing the iterator since the recursive implementation is easier to understand and implement.

Assume we have a populated binary search tree bst. The following statement must print the values in the BST "in order":

bst.printInOrder();

Exercise Complete the implementation of printInOrder.

public void printInOrder() {
  printInOrder(root);
}

private void printInOrder(Node<T> node) {
  // TODO: Implement me!
}
Solution
private void printInOrder(Node<T> node) {
  // if null: base case, do nothing
  if (node != null) {
    printInOrder(node.left);
    System.out.print(node.data + " ");
    printInOrder(node.right);
  }
}