Print a binary tree in a pretty way

In order to pretty-print a tree recursively, you need to pass two arguments to your printing function:

  • The tree node to be printed, and
  • The indentation level

For example, you can do this:

void BinarySearchTree::postorder(tree_node* p, int indent=0)
{
    if(p != NULL) {
        if(p->left) postorder(p->left, indent+4);
        if(p->right) postorder(p->right, indent+4);
        if (indent) {
            std::cout << std::setw(indent) << ' ';
        }
        cout<< p->data << "\n ";
    }
}

The initial call should be postorder(root);

If you would like to print the tree with the root at the top, move cout to the top of the if.

Leave a Comment