Printing BFS (Binary Tree) in Level Order with Specific Formatting

前端 未结 15 1416
情歌与酒
情歌与酒 2020-12-04 13:00

To begin with, this question is not a dup of this one, but builds on it.

Taking the tree in that question as an example,

    1 
   / \\
  2   3
 /            


        
15条回答
  •  醉酒成梦
    2020-12-04 13:31

    Here my code prints the tree level by level as well as upside down

    int counter=0;// to count the toatl no. of elments in the tree
    
    void tree::print_treeupsidedown_levelbylevel(int *array)
    {
        int j=2;  
        int next=j;
        int temp=0;
        while(j<2*counter)
        {
            if(array[j]==0)
            break;
    
            while(array[j]!=-1)
            {
                j++;
            }
    
            for(int i=next,k=j-1 ;i=0;i--)
        {
            if(array[i]>0)
            printf("%d ",array[i]);
    
            if(array[i]==-1)
            printf("\n");
        }
    }
    
    void tree::BFS()
    {
        queuep;
    
        node *leaf=root;
    
        int array[2*counter];
        for(int i=0;i<2*counter;i++)
        array[i]=0;
    
        int count=0;
    
        node *newline=new node; //this node helps to print a tree level by level
        newline->val=0;
        newline->left=NULL;
        newline->right=NULL;
        newline->parent=NULL;
    
        p.push(leaf);
        p.push(newline);
    
        while(!p.empty())
        {
            leaf=p.front();
            if(leaf==newline)
            {
                printf("\n");
                p.pop();
                if(!p.empty())
                p.push(newline);
                array[count++]=-1;
            }
            else
            {
                cout<val<<" ";
                array[count++]=leaf->val;
    
                if(leaf->left!=NULL)
                {
                    p.push(leaf->left);
                }
                if(leaf->right!=NULL)
                {
                    p.push(leaf->right);
                }
                p.pop();
            }
        }
        delete newline;
    
        print_treeupsidedown_levelbylevel(array);
    }
    

    Here in my code the function BFS prints the tree level by level, which also fills the data in an int array for printing the tree upside down. (note there is a bit of swapping is used while printing the tree upside down which helps to achieve our goal). If the swapping is not performed then for a tree like

                        8
                       /  \
                      1    12
                      \     /
                       5   9
                     /   \
                    4     7
                         /
                        6
    

    o/p will be

      6
      7 4
      9 5
      12 1
      8
    

    but the o/p has to be

      6
      4 7
      5 9
      1 12
      8
    

    this the reason why swapping part was needed in that array.

提交回复
热议问题