洛谷 P1305 新二叉树 (dfs / 树的前序遍历)

https://www.luogu.com.cn/problem/P1305

题目描述
给定二叉树的节点数为 n。

n 行,每第一个字母为根节点,后两个字母分别为其左右儿子。

【特别地,数据保证第一行读入的节点必为根节点。】

空节点用 * 表示

输出二叉树的前序遍历。
输入输出样例
输入 #1复制
6
abc
bdi
cj*
d**
i**
j**
输出 #1复制
abdicj
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=200200,M=2002;
int n;
char a[N][4];
void dfs(char x)
{
    if(x!='*')//不是叶子节点才能进去
    {
        cout<<x;
        for(int i=1;i<=n;i++)
        {
            if(a[i][0]==x)
            {
                dfs(a[i][1]);//从a到b到d到*。。。(左子树一直往下遍历)
                dfs(a[i][2]);//(右子树一直往下遍历)
            }
        }
    }
    return ;
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        //给定根节点,左子树,右子树
        cin>>a[i][0]>>a[i][1]>>a[i][2];
    }
    dfs(a[1][0]);//从根节点开始遍历(已知题目把1定义为根节点)
    return 0;
}
posted @ 2022-09-15 15:45  Vijurria  阅读(76)  评论(0)    收藏  举报