题目描述
输入一串二叉树,输出其前序遍历。
输入格式
第一行为二叉树的节点数 n。(1=<n<=26)
后面 n 行,每一个字母为节点,后两个字母分别为其左右儿子。
空节点用 * 表示
输出格式
二叉树的前序遍历。
输入输出样例
输入 #1
6
abc
bdi
cj*
d**
i**
j**
输出 #1
abdicj
直接将字母转化为对应的数字作为下标就可以巧妙解决
#include<iostream>
#include<map>
#include<cstdio>
using namespace std;
struct node{
int left;
int right;
};
node tree[1000005];
int n;
string str;
char t;
void dfs(int node){
if(node+'0'=='*'){
return;
}
printf("%c",node+'0');
dfs(tree[node].left);
dfs(tree[node].right);
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>str;
if(i==0){
t=str[0];
}
tree[str[0]-'0'].left=str[1]-'0';
tree[str[0]-'0'].right=str[2]-'0';
}
dfs(t-'0');
return 0;
}