【例题 6-7 UVA - 122 】Trees on the level

本文介绍了一种使用数组存储二叉树的方法,并通过广度优先搜索(BFS)来构建和遍历二叉树,实现从字符串描述中构建完整的二叉树结构并输出节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【链接】 我是链接,点我呀:)
【题意】


在这里输入题意

【题解】


二叉树的话,直接用数组存就好了。
写个bfs记录一下答案。

【代码】

#include <bits/stdc++.h>
using namespace std;

const int N = 300;

string s;
int g[N+10][3],cnt;
vector <int> ans;

bool bfs(){
    queue <int> dl;
    dl.push(0);

    while (!dl.empty()){
        int x = dl.front();
        dl.pop();
        if (!g[x][2])   return false;
        ans.push_back(g[x][2]);
        for (int i = 0;i < 2;i++)
            if (g[x][i])
                dl.push(g[x][i]);
    }
    return true;
}

int main(){
//  freopen("rush.txt","r",stdin);
    while (cin >> s){
        ans.clear();
        memset(g,0,sizeof g);
        cnt = 0;
        bool ok = true;
        while (!(s[0]=='(' && s[1]==')')){
            int len = s.size();
            bool root = false;
            for (int i = 0;i < len;i++)
                if (s[i]=='(' || s[i]==')' || s[i]==',') {
                    if (s[i]==',' && i+1<len && s[i+1]==')') root = true;
                    s[i]=' ';
                }
            stringstream ss(s);
            int x;
            ss >> x >> s;
            if (root) s = "";
            int now = 0;
            for (int i = 0;i < (int) s.size();i++){
                if (s[i]=='L'){
                    if (!g[now][0]) g[now][0] = ++cnt;
                    now = g[now][0];
                }else{
                    if (!g[now][1]) g[now][1] = ++cnt;
                    now = g[now][1];        
                }
            } 
            if (g[now][2]==0)
                g[now][2] = x;
            else{
                ok = false;
            }
            cin >> s;
        }
        if (!ok || !bfs()){
            puts("not complete");
        }else{
            for (int i = 0;i < (int) ans.size();i++){
                printf("%d",ans[i]);
                if (i==(int)ans.size()-1){
                    puts("");
                }else putchar(' ');
            }
        }
    }   
    return 0;
}

转载于:https://www.cnblogs.com/AWCXV/p/7701253.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值