P1305
新二叉树
题目描述
输入一串二叉树,输出其前序遍历。
输入格式
第一行为二叉树的节点数 \(n\)。(\(1 \leq n \leq 26\))
后面 \(n\) 行,每一个字母为节点,后两个字母分别为其左右儿子。特别地,数据保证第一行读入的节点必为根节点。
空节点用 * 表示
输出格式
二叉树的前序遍历。
样例 #1
样例输入 #1
6
abc
bdi
cj*
d**
i**
j**
样例输出 #1
abdicj
关于建树以及遍历的一些小细节
点击查看代码
#include<bits/stdc++.h>
using namespace std;
struct did{
char lc,rc;
}tr[1005];
int n;
void dfs(char x)
{
if(x=='*')return ;
cout<<x;
dfs(tr[x].lc);
dfs(tr[x].rc);
}
int main()
{
ios::sync_with_stdio(false);
cin>>n;
char root;
cin>>root;
cin>>tr[root].lc>>tr[root].rc;
// cout<<root<<" "<<tr[root].lc<<" "<<tr[root].rc<<"\n";
for(int i=2;i<=n;i++)
{
char ch;
cin>>ch;
cin>>tr[ch].lc>>tr[ch].rc;
}
dfs(root);
return 0;
}
此生无悔入OI 来生AK IOI

浙公网安备 33010602011771号