建立一棵二叉树 输出前序

/*
洛谷 p1305
输入一串二叉树,用遍历前序打出。
第一行为二叉树的节点数n。(n \leq 26n≤26)
后面n行,每一个字母为节点,后两个字母分别为其左右儿子。
空节点用*表示
6
abc
bdi
cj*
d**
i**
j** 
输出:abdicj
思路:建立一个节点包含父节点 左儿子 右儿子 的节点(有父节点可以判断谁是根结点) 
*/
#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int N=100;
struct node
{
	int fa,l,r;
}tree[N];
int cnt;
map<char,int>ci;
map<int,char>ic;
void dfs(int x)
{
	if(x!=inf){
		printf("%c",ic[x]);
		dfs(tree[x].l);
		dfs(tree[x].r);
	}
	else return;
}
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		char s[4];
		scanf("%s",s);
		int f;
		if(ci[s[0]]==0){
			ci[s[0]]=++cnt;
			ic[cnt]=s[0];
			f=cnt;
		}
		else{
			f=ci[s[0]];
		}
		if(s[1]=='*'){
			tree[f].l=inf;
		}
		else{
			if(ci[s[1]]==0){
				ci[s[1]]=++cnt;
				ic[cnt]=s[1];
				tree[f].l=cnt;
				tree[cnt].fa=f;
			}
			else{
				tree[f].l=ci[s[1]];
				tree[ci[s[1]]].fa=f;
			}
		}
		if(s[2]=='*'){
			tree[f].r=inf;
		}
		else{
			if(ci[s[2]]==0){
				ci[s[2]]=++cnt;
				ic[cnt]=s[2];
				tree[f].r=cnt;
				tree[cnt].fa=f;
			}
			else{
				tree[f].l=ci[s[2]];
				tree[ci[s[2]]].fa=f;
			}
		}
	}
	int id=0;
	for(int i=1;i<=cnt;i++){
		if(tree[i].fa==0){
			id=i;
			break;
		}
	}
	dfs(id);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/CC_1012/article/details/92798163
今日推荐