【二叉树】hdu 1622 Trees on the level

【题意】

给定一棵树每个结点的权重和路径(路径用LR串表示),输出这棵树的层次遍历

【思路】

注意输入输出,sscanf用来格式化地截取需要的数据,strchr来在字符串中查找字符的位置

【Accepted】

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;

int num;
const int maxn=300;
char str[maxn];
struct node{
    int num;
    node *lef;
    node *rig;
};
node *root;
bool tag;
void bfs(node *rt){
    queue<node *> Q;
    Q.push(rt);
    while(!Q.empty()){
        node *q=Q.front();
        Q.pop();
        if(q==rt){
            printf("%d",q->num);
        }else{
            printf(" %d",q->num);
        }
        if(q->lef){
            Q.push(q->lef);
        }
        if(q->rig){
            Q.push(q->rig);
        }
        free(q);
    }
}
bool isComplete(node *rt){
    queue<node *> Q;
    Q.push(rt);
    while(!Q.empty()){
        node *q=Q.front();
        Q.pop();
        if(q->num==-1){
            return false;
        }
        if(q->lef!=NULL){
            Q.push(q->lef);
        }
        if(q->rig!=NULL){
            Q.push(q->rig);
        }
    }
    return true;
}
void print(node *root){
    if(tag==false){
        printf("not complete\n");
        return;
    }
    bool flag=isComplete(root);
    if(!flag){
        printf("not complete\n");
        return;
    }
    bfs(root);
    puts("");
}
int main(){
    root=(node *)malloc(sizeof(node));
    root->num=-1;
    root->lef=NULL;
    root->rig=NULL;
    tag=true;
    while(scanf("%s",str)!=EOF){
        if(!strcmp(str,"()")){
            print(root);
            root=(node *)malloc(sizeof(node));
            root->num=-1;
            root->lef=NULL;
            root->rig=NULL;
            tag=true;
        }else{
            sscanf(&str[1],"%d",&num);
        //    printf("%d\n",num);
            char *comma=strchr(str,',');
            char *path=comma+1;
            node *now=root;
            for(char *i=path;*i!=')';i++){
                if(*i=='L'){
                    if(now->lef==NULL){
                        node *nd=(node *)malloc(sizeof(node));
                        nd->num=-1;
                        nd->lef=NULL;
                        nd->rig=NULL;
                        now->lef=nd;
                    }
                    now=now->lef;
                }else{
                    if(now->rig==NULL){
                        node *nd=(node *)malloc(sizeof(node));
                        nd->num=-1;
                        nd->lef=NULL;
                        nd->rig=NULL;
                        now->rig=nd;
                    }
                    now=now->rig;
                }
            }
            if(now->num!=-1){
                tag=false; 
            }else{
                now->num=num;
            }
        }
    }
    free(root);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/itcsl/p/9175785.html