Print a binary tree in a pretty way

后端 未结 15 1278
我寻月下人不归
我寻月下人不归 2020-11-28 22:15

Just wondering if I can get some tips on printing a pretty binary tree in the form of:

5
     10
          11
          7
               6
     3
          4         


        
15条回答
  •  情深已故
    2020-11-28 22:39

    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.

提交回复
热议问题