洛谷 P1305 新二叉树(树的遍历)

题目描述

输入一串二叉树,输出其前序遍历。

输入格式

第一行为二叉树的节点数 nn。(1 \leq n \leq 261≤n≤26)

后面 nn 行,每一个字母为节点,后两个字母分别为其左右儿子。

空节点用 * 表示

输出格式

二叉树的前序遍历。

输入输出样例

输入 

6
abc
bdi
cj*
d**
i**
j**

输出 

abdicj

代码:

#include <iostream>
using namespace std;
int n;
string tree[27];
void first_order(int i)//i为第i行字符串 
{
	cout<<tree[i][0];
	if(tree[i][1]!='*')//搜索左子树 
	{
		for(int j=0;j<n;j++)
		{
			if(tree[j][0]==tree[i][1])
			first_order(j);
		 } 
	} 
	if(tree[i][2]!='*')//搜索右子树 
	{
		for(int j=0;j<n;j++)
		{
			if(tree[j][0]==tree[i][2])
			{
				first_order(j);
			}
		}
	}
}
int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	cin>>tree[i];
	first_order(0);
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/xiaolan7777777/article/details/104397345