Print binary tree in a pretty way using c++

前端 未结 4 1443
广开言路
广开言路 2021-02-01 09:03

I am a \"bit\" lost trying to print a binary tree like below in c++:

            8
           / \\
          /   \\
         /     \\
        5       10
       /         


        
4条回答
  •  面向向阳花
    2021-02-01 09:42

    Even tough it is not exactly what you asked for, printing trees horizontally is way simpler. And especially in case of large trees, I think this is the better representation form.

    └──8
       ├──5
       │   ├──2
       │   └──6
       └──10
           ├──9
           └──11
    

    Following C++ code roots in this java implementation.

    void printBT(const std::string& prefix, const BSTNode* node, bool isLeft)
    {
        if( node != nullptr )
        {
            std::cout << prefix;
    
            std::cout << (isLeft ? "├──" : "└──" );
    
            // print the value of the node
            std::cout << node->m_val << std::endl;
    
            // enter the next tree level - left and right branch
            printBT( prefix + (isLeft ? "│   " : "    "), node->m_left, true);
            printBT( prefix + (isLeft ? "│   " : "    "), node->m_right, false);
        }
    }
    
    void printBT(const BSTNode* node)
    {
        printBT("", node, false);    
    }
    
    // pass the root node of your binary tree
    printBT(root);
    

提交回复
热议问题