UVa122树的层次遍历,字符串处理,队列

题目大意:给定一个序列,形如:(2,L) (3,R) (4,LLR) (5,) (),前一部分是节点的值,后一部分表示该节点在树中的位置,相邻节点之间有一个空格隔开,位置从根节点开始算起。现在要求你根据该序列构建出一棵树并层序输出。如果过程中有一个节点多次赋值或有节点没有赋值的输出-1,否则直接输出层序遍历结果。

样例输入:(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()

样例输出:5 4 8 11 13 4 7 2 1

下面给出我用c实现的代码:

这里只给出了单例的代码,如需符合多例,读者可自行修改!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node{//定义数据结构
    int haveValue;
    int value;
    struct node* left;
    struct node* right;
}Node;

Node* root;
Node* nodes[260];
int failed = 0;//失败标志
int front = 0,rail = 0;//队列前后指针
int values[260],end = 0;//临时存放遍历队值,以防有不合格的情况

Node* newNode(){//申请一个新节点
    Node* n = (Node*)malloc(sizeof(Node));
    n->haveValue = 0;
    n->left = NULL;
    n->right = NULL;
    return n;
}

void addNode(char str[],int v){//每读一条数据就添加一个节点
    Node* n = root;
    int i;
    for(i=0;str[i] != '\0';i++){
        if(str[i] == 'L'){
            if(n->left == NULL)
                n->left = newNode();
            n = n->left;
        }else if(str[i] == 'R'){
            if(n->right == NULL)
                n->right = newNode();
            n = n->right;
        }
    }
    if(n->haveValue == 1)failed = 1;
    n->haveValue = 1;
    n->value = v;
}

void read(){//读取数据
    char str[20];
    root = newNode();
    while(1){
        if(scanf("%s",str) != 1)break;
        if(strcmp(str,"()") == 0)break;
        int v;
        sscanf(str+1,"%d",&v);
        addNode(strchr(str,',')+1,v);
    }
}

void push(Node* n){//模拟队列入队
    nodes[rail++] = n;
}

Node* pop(){//模拟队列出队
    return nodes[front++];
}

int empty(){//判断一个队列是否为空
    return front == rail;
}

void bfs(){//广度优先遍历
    if(empty())return;
    Node* n = pop();
    if(n->haveValue == 0){failed = 1;return;}
    values[end++] = n->value;
    if(n->left != NULL)push(n->left);
    if(n->right != NULL)push(n->right);
    bfs();
}

void show(){//显示最后的输出数据
    if(failed){printf("-1\n");return; }
    int i;
    for(i=0;i<end;i++)
        printf("%d ",values[i]);
    printf("\n");
}

void remove_tree(Node* n){//一定不要忘记最后释放整棵树
    if(n == NULL)return;
    remove_tree(n->left);
    remove_tree(n->right);
    free(n);
}

int main(){
    read();
    push(root);
    bfs();
    show();
    remove_tree(root);
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值