P1305 新二叉树【递归】

新二叉树

题目描述

输入一串二叉树,输出其前序遍历。

输入格式

第一行为二叉树的节点数 n n n。( 1 ≤ n ≤ 26 1 \leq n \leq 26 1n26)

后面 n n n 行,每一个字母为节点,后两个字母分别为其左右儿子。特别地,数据保证第一行读入的节点必为根节点。

空节点用 * 表示

输出格式

二叉树的前序遍历。

样例 #1

样例输入 #1

6
abc
bdi
cj*
d**
i**
j**

样例输出 #1

abdicj

问题链接: P1305 新二叉树
问题分析: 递归问题,不解释。
参考链接: (略)
题记: (略)

AC的C++语言程序如下:

/* P1305 新二叉树 */

#include <iostream>

using namespace std;

const int N = 26;
string a[N];
int n;

void f(char x)
{
    
    
    if (x != '*') {
    
    
        cout << x;
        for (int i = 0; i < n; i++)
            if (a[i][0] == x) {
    
    
                f(a[i][1]);
                f(a[i][2]);
            }
    }
}

int main()
{
    
    
    cin >> n;
    for (int i = 0; i < n; i++)
        cin >> a[i];
    f(a[0][0]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/140969237