1 solutions

  • 0
    @ 2024-12-10 22:44:37

    C++ :

    #include<iostream>  
    #define MX 1010  
    using namespace std;  
    int a[MX];  
    typedef struct node  
    {  
        int data;  
        struct node *lchild,*rchild;  
    }node,*Btree;  
    void create(Btree &t,int i){  
        if(i>a[0]||a[i]==0){t=NULL;return ;}  
        t=new node;  
        t->data=a[i];  
        create(t->lchild,2*i);  
        create(t->rchild,2*i+1);  
    }  
    void preorder(Btree t)  
    {  
        if(t)  
        {  
      
            preorder(t->lchild);  
            preorder(t->rchild);  
            cout<<" "<<t->data;  
        }  
    }  
    int depth(Btree t)  
    {  
        int dep=0,depl,depr;  
        if(!t)dep=0;  
        else  
        {  
            depl=depth(t->lchild);  
            depr=depth(t->rchild);  
            dep=1+(depl>depr?depl:depr);  
        }  
        return dep;  
    }  
    int main()  
    {  
        Btree t;  
        int dep,n,x;  
        cin>>n;  
        while(n--){  
            a[0]=0;  
            while(cin>>x&&x!=-1)a[++a[0]]=x;  
            create(t,1);  
            dep=depth(t);  
            cout<<dep;  
            preorder(t);  
            cout<<endl;  
        }  
        return 0;  
    }  
    
    • 1

    Information

    ID
    555
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    (None)
    Tags
    (None)
    # Submissions
    0
    Accepted
    0
    Uploaded By