Search code examples
c++algorithmrecursiontreepreorder

Formatting output of tree contents - Preorder traversal


I have a method to print the contents of a tree:

void RedBlackTree::printPreorder(RedBlackNode *root){
    if(root == NULL) 
        return;
    cout << root->data << endl;
    printInorder(root->left);
    printInorder(root->right);
}

The contents of my tree are reading out correctly, but I want to format the tree so that it looks nicer. Right now, for a tree:

    c
   / \
  b   k
 /   / \
a   d   m

The contents print:

c
b
a
k
d
m

But I'd like to add some indentation, so that it reads:

c
    b
        a
    k
        d
        m

The format would be:

Root
    Left 
        LeftLeft
        LeftRight
    Right
        RightLeft
        RightRight

etc....

I'm just getting a bit lost with the recursion. Thanks!


Solution

  • void RedBlackTree::printPreorder(RedBlackNode *root, int depth){
        if(root == NULL) 
            return;
        for(int i=0; i<=depth; i++)
          cout <<" ";
    
        depth++;
        cout << root->data << endl;
        printInorder(root->left, depth);
        printInorder(root->right, depth);
    }  
    

    Give it a try!!