题目链接
题目描述
输入一串二叉树,用遍历前序打出。
输入输出格式
输入格式:第一行为二叉树的节点数n。( n \leq 26n≤26 )
后面n行,每一个字母为节点,后两个字母分别为其左右儿子。
空节点用*表示
输出格式:前序排列的二叉树
输入输出样例
输入样例#1:
6 abc bdi cj* d** i** j**
输出样例#1:
abdicj
思路:
简单的二叉树先序遍历,关键我是个不会字符类各种知识的蒟蒻,只好粗糙的把char转int……
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define maxn 250 #define loop( i, a, b ) for( int i = a; i <= b; i++ ) using namespace std; int n, kong = '*' - '0'; int f[maxn], v[maxn], l[maxn], r[maxn]; void haha_tree() { char p, lc, rc; scanf( "%d", &n ); loop( i, 1, n ) { cin>>p>>lc>>rc; int llc, rrc, pp; pp = p - '0'; //粗糙的转化。 llc = lc - '0'; rrc = rc - '0'; if( llc != kong ) { f[llc] = pp; l[pp] = llc; } if( rrc != kong ) { f[rrc] = pp; r[pp] = rrc; } } } inline int find_root() { //为什么逼我写板子? int aa = 'a' - '0'; //依旧粗糙。 int bb = 'z' - '0'; loop( i, aa, bb ) if( f[i] == 0 ) return i; } inline void xianxu( int i ) { if( i ) { char ans; ans = i + '0'; cout<<ans; xianxu( l[i] ); xianxu( r[i] ); } } int main() { haha_tree(); int gen = find_root(); xianxu( gen ); return 0; }