题解 P1305 【新二叉树】
题目描述
输入一串二叉树,输出其前序遍历。
输入格式
第一行为二叉树的节点数 n。(1 <= n <= 261≤n≤26)
后面 n 行,每一个字母为节点,后两个字母分别为其左右儿子。
空节点用 * 表示
输出格式
二叉树的前序遍历。
输入输出样例
输入
6
abc
bdi
cj*
d**
i**
j**
输出
abdicj
这道题不难,可以使用一些技巧来完成。但蒟蒻还是使用了最简单粗暴的方法:直接建树。
输入数据后建树,然后直接前序遍历就完成了。
上代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 30;
struct Node {
char data;
int ls, rs;
}tree[maxn];
int n;
string s[30];
void qx(int x) {
cout << tree[x].data;
if(tree[x].ls) qx(tree[x].ls);
if(tree[x].rs) qx(tree[x].rs);
}
int main () {
cin >> n;
for(int i = 1; i <= n; i++)
cin >> s[i];
for(int i = 1; i <= n; i++) {
tree[i].data = s[i][0];
if(s[i][1] != '*') {
for(int j = 1; j <= n; j++)
if(s[j][0] == s[i][1]) {
tree[i].ls = j;
break;
}
}
if(s[i][2] != '*') {
for(int j = i + 1; j <= n; j++)
if(s[j][0] == s[i][2]) {
tree[i].rs = j;
break;
}
}
}
qx(1);
return 0;
}

浙公网安备 33010602011771号