UVA - 122 Trees on the level(二叉树的构建+宽度优先遍历)

点击打开题目链接
层序遍历输出二叉树节点值。
存储结构可以是结构体+指针,也可以数组+下标
lrj代码对字符串的处理比较灵活。
代码:

#include<bits/stdc++.h>

using namespace std;
const int maxn = 256 + 5;
const int root = 1;
vector<int>ve;
int l[maxn], r[maxn];
int cnt;
int val[maxn], have_val[maxn];
char s[maxn];
int failed;

void newtree() {
    l[root] = r[root] = 0;
    have_val[root] = 0;
    cnt = root;
}

int newnode() {
    int u = ++cnt;
    l[u] = r[u] = 0;
    have_val[u] = 0;
    return u;
}

void addnode(int v, char str[]) {
    int len = strlen(str);
    int u = root;
    for(int i = 0; i < len; i++) {
        if(str[i] == 'L') {
            if(l[u] == 0) l[u] = newnode();
            u = l[u];
        }
        else if(str[i] == 'R') {
            if(r[u] == 0) r[u] = newnode();
            u = r[u];
        }
    }
    if(have_val[u]) failed = 1;
    val[u] = v;
    have_val[u] = 1;
}

int read_input() {
    failed = 0;
    newtree();
    for(;;) {
        if(scanf("%s", s) != 1) return 0;
        if(!strcmp(s, "()")) break;
        int v;
        sscanf(&s[1], "%d", &v);
        addnode(v, strchr(s, ',') + 1);
    }
    return 1;
}

int bfs(vector<int>& ve) {
    ve.clear();
    queue<int> q;
    q.push(root);
    while(!q.empty()) {
        int t = q.front(); q.pop();
        if(!have_val[t]) return 0;
        ve.push_back(val[t]);
        if(l[t]) q.push(l[t]);
        if(r[t]) q.push(r[t]);
    }
    return 1;
}

int main() {
    //ios::sync_with_stdio(false);
    while(read_input()) {
        if(failed == 1) printf("not complete\n");
        else {
            int t = bfs(ve);
            if(t == 0) printf("not complete\n");
            else {
                for(int i = 0; i < ve.size(); i++)  {
                    if(i == 0) printf("%d",ve[i]);
                    else printf(" %d", ve[i]);
                }
                puts("");
            }
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chook_lxk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值