[sicily online]1156. Binary tree(递归先序遍历)

//用map来存储图
//递归先序遍历
#include<iostream>
#include<set>
#include<vector>
#include<map>
using namespace std;

typedef struct NODE
{
	char value;
	int parent;
	int lchild;
	int rchild;
	//struct NODE():value('\0'),parent(0),lchild(0),rchild(0){}
}Node;

void pre(map<int,Node> &gra,int index)
{
	cout<<gra[index].value;
	if(gra[index].lchild!=0)
		pre(gra,gra[index].lchild);
	if(gra[index].rchild!=0)
		pre(gra,gra[index].rchild);
}

int main()
{
	int n;
	while(cin>>n)
	{
		map<int,Node>gra;
		for(int i=0;i<n;i++)
		{
			int index;
			cin>>index;
			cin>>gra[index].value>>gra[index].lchild>>gra[index].rchild;
			gra[gra[index].lchild].parent=index;
			gra[gra[index].rchild].parent=index;
		}
		map<int,Node>::iterator ite;
		int tmpIndex=0;
		for(ite=gra.begin();ite!=gra.end();ite++)
		{
			if(ite->second.parent==0)
			{
				tmpIndex=ite->first;
				break;
			}
		}
		pre(gra,tmpIndex);
		cout<<endl;
	}//end while
}

你可能感兴趣的:([sicily online]1156. Binary tree(递归先序遍历))