洛谷1305
求二叉树的先序遍历。
#include<iostream>
#include<string>
using namespace std;
struct node{
int fa, l,r;
}tree[30];
string c;
void vis(int rt){
cout<<char(rt+96);
if(tree[rt].l!=0)vis(tree[rt].l);
if(tree[rt].r!=0)vis(tree[rt].r);
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>c;
if(c[1]!='*'){
tree[c[0]-96].l=c[1]-96;
tree[c[1]-96].fa=c[0]-96;
}
if(c[2]!='*'){
tree[c[0]-96].r=c[2]-96;
tree[c[2]-96].fa=c[0]-96;
}
}
int root;
for(int i=1;i<=26;i++){
if(tree[i].fa==0){
root=i;
break;
}
}
vis(root);
return 0;
}