Print a binary tree in a pretty way

后端 未结 15 1270
我寻月下人不归
我寻月下人不归 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:58

    Here is my code. It prints very well,maybe its not perfectly symmetrical. little description:

    • 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

提交回复
热议问题