Print a binary tree in a pretty way

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

    #include 
    #include 
    
    struct Node
    {
        struct Node *left,*right;
        int val;
    } *root=NULL;
    
    int rec[1000006];
    void addNode(int,struct Node*);
    void printTree(struct Node* curr,int depth)
    {
        int i;
        if(curr==NULL)return;
        printf("\t");
        for(i=0;ival);
        rec[depth]=1;
        printTree(curr->left,depth+1);
        rec[depth]=0;
        printTree(curr->right,depth+1);
    }
    int main()
    {
        root=(struct Node*)malloc(sizeof(struct Node));
        root->val=50;
        //addNode(50,root);
        addNode(75,root);    addNode(25,root);
        addNode(15,root);    addNode(30,root);
        addNode(100,root);    addNode(60,root);
        addNode(27,root);    addNode(31,root);
        addNode(101,root);    addNode(99,root);
        addNode(5,root);    addNode(61,root);
        addNode(55,root);    addNode(20,root);
        addNode(0,root);    addNode(21,root);
        //deleteNode(5,root);
    
        printTree(root,0);
        return 0;
    }
    
    void addNode(int v,struct Node* traveller)
    {
        struct Node *newEle=(struct Node*)malloc(sizeof(struct Node));
        newEle->val=v;
        for(;;)
        {
            if(vval)
            {
                if(traveller->left==NULL){traveller->left=newEle;return;}
                traveller=traveller->left;
            }
            else if(v>traveller->val)
            {
                if(traveller->right==NULL){traveller->right=newEle;return;}
                traveller=traveller->right;
            }
            else
            {
                printf("%d Input Value is already present in the Tree !!!\n",v);
                return;
            }
        }
    }
    

    Hope, you find it pretty...

    Output:

    50
    ͱ———25
    ⎸   ͱ———15
    ⎸   ⎸   ͱ———5
    ⎸   ⎸   ⎸   ͱ———0
    ⎸   ⎸   ∟———20
    ⎸   ⎸        ∟———21
    ⎸   ∟———30
    ⎸        ͱ———27
    ⎸        ∟———31
    ∟———75
         ͱ———60
         ⎸   ͱ———55
         ⎸   ∟———61
         ∟———100
              ͱ———99
              ∟———101
    

提交回复
热议问题