UVa 10562看图写树(二叉树遍历)

UVA在线评测二叉树遍历问题解析
本文解析了UVA在线评测中一道关于二叉树遍历的问题,通过使用C++实现DFS深度优先搜索算法来解决该题目。文章详细介绍了如何读取输入并构造二叉树,以及如何通过递归方式完成遍历。

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1503

这道题错了好多次,一开始我直接是cin>>t,但前面可能还有空格,所以不对。就按照书上的用了fgets(buf[0],maxn,stdin)。

题目的本质就是二叉树的遍历问题,直接运用dfs遍历即可。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cctype>
 4 using namespace std;
 5 
 6 const int maxn = 220;
 7 char buf[maxn][maxn];
 8 int n;
 9 
10 void dfs(int r, int i)
11 {
12     cout << buf[r][i];
13     cout << "(";
14     if (r + 1<n && buf[r + 1][i] == '|')
15     {
16         int k = i;
17         while (k - 1 >= 0 && buf[r + 2][k - 1] == '-')  k--;
18         while (buf[r + 2][k] == '-' && buf[r+3][k]!='\0')
19         {
20             if (!isspace(buf[r + 3][k])) dfs(r + 3, k);
21             k++;
22         }
23     }
24     cout << ")";
25 }
26 void solve()
27 {
28     n = 0;
29     for (;;)
30     {
31         fgets(buf[n], maxn, stdin);
32         if (buf[n][0] == '#') break;
33         else n++;
34     }
35     cout << "(";
36     if (n)
37     {    
38         int l = strlen(buf[0]);
39         for (int i = 0; i < l; i++)
40             if (buf[0][i] != ' ')    { dfs(0, i); break; }
41     }
42     cout << ")"<<endl;
43 }
44 
45 int main()
46 {
47     int t;
48     fgets(buf[0], maxn, stdin);
49     sscanf(buf[0], "%d", &t);
50     while (t--)  solve();
51     return 0;
52 }

 

转载于:https://www.cnblogs.com/zyb993963526/p/6178952.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值