Uva10562 Undraw the Trees 【递归建树】【例题6-17】

题目:Undraw the Trees

题意:将多叉树转化为括号表示法。每个结点用除了“-”“|”和空格的其他字符表示,每个非叶结点的正下方总会有一个“|”字符,然后下方是一排“-”字符,恰好覆盖所有子结点的上方。 单独的一行“#”为数据结束标记。

思路:直接将二维数组递归建树即可。(但是自己还是没想出来。。。)

参考:入门经典-例6-17-P268

代码:

#include <iostream>
#include <stdio.h>
using namespace std;
const int maxn = 205;
char str[maxn][maxn];
int n;
void dfs(int row,int col){
    printf("%c(",str[row][col]);//输入当前结点
    if(row+1 < n && str[row+1][col] == '|'){//判断有子结点
        int i = col;
        while(i-1 >= 0 && str[row+2][i-1] == '-') i--;//找---左边界
        while(str[row+2][i] == '-' && str[row+3][i]!='\0'){//将子结点再进行递归,且在---范围内
            if(!isspace(str[row+3][i])) dfs(row+3,i);
            i++;
        }
    }
    printf(")");
}
void solve(){
    n = 0;
    while(cin.getline(str[n++],maxn) && str[n-1][0] != '#');//输入
    n--;
    printf("(");
    if(n)
        for(int j=0;str[0][j] !='\0';j++)//找到根结点进行递归
            if(!isspace(str[0][j])){dfs(0,j);break;}
    printf(")\n");
}
int main()
{
    int t;
    scanf("%d",&t);getchar();
    while(t--) solve();
    return 0;
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值