Print a binary tree in a pretty way

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

    i have a easier code.......... consider a tree made of nodes of structure

     struct treeNode{
      treeNode *lc;
      element data;
      short int bf;
      treeNode *rc;
    };
    

    Tree's depth can be found out using

    int depth(treeNode *p){
        if(p==NULL) return 0;
        int l=depth(p->lc);
        int r=depth(p->rc);
        if(l>=r)
            return l+1;
        else
            return r+1;
    }
    

    below gotoxy function moves your cursor to the desired position

    void gotoxy(int x,int y)
    {
    printf("%c[%d;%df",0x1B,y,x);
    }
    

    Then Printing a Tree can be done as:

    void displayTreeUpDown(treeNode * root,int x,int y,int px=0){
    if(root==NULL) return;
    gotoxy(x,y);
    int a=abs(px-x)/2;
    cout<data.key;
    displayTreeUpDown(root->lc,x-a,y+1,x);
    displayTreeUpDown(root->rc,x+a,y+1,x);
    }
    

    which can be called using:

    display(t,pow(2,depth(t)),1,1);
    

提交回复
热议问题