Print binary tree in a pretty way using c++

前端 未结 4 1436
广开言路
广开言路 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:48

    • 1st function - prints level by level (root lv -> leaves lv)
    • 2nd function - distance from the beginning of new line
    • 3rd function - prints nodes and calculates distance between two prints;

    void Tree::TREEPRINT()
    {
        int i = 0;
        while (i <= treeHeight(getroot())){
            printlv(i);
            i++;
            cout << endl;
        }
    }
    
    void Tree::printlv(int n){
        Node* temp = getroot();
        int val = pow(2, treeHeight(root) -n+2);
        cout << setw(val) << "";
        prinlv(temp, n, val);
    }
    
    void Tree::dispLV(Node*p, int lv, int d)
    {
        int disp = 2 * d;
        if (lv == 0){
            if (p == NULL){
    
                cout << " x ";
                cout << setw(disp -3) << "";
                return;
            }
            else{
                int result = ((p->key <= 1) ? 1 : log10(p->key) + 1);
                cout << " " << p->key << " ";
                cout << setw(disp - result-2) << "";
            }
        }
        else
        {
            if (p == NULL&& lv >= 1){
                dispLV(NULL, lv - 1, d);
                dispLV(NULL, lv - 1, d);
            }
            else{
                dispLV(p->left, lv - 1, d);
                dispLV(p->right, lv - 1, d);
            }
        }
    }   
    

    Input:

    50-28-19-30-29-17-42-200-160-170-180-240-44-26-27
    

    Output: https://i.stack.imgur.com/TtPXY.png

提交回复
热议问题