扩展二叉树

http://wlacm.com/problem.php?cid=1238&pid=4

题目描述

由于先序、中序和后序序列中的任一个都不能唯一确定一棵二叉树,所以对二叉树做如下处理,将二叉树的空结点用·补齐,如图所示。我们把这样处理后的二叉树称为原二叉树的扩展二叉树,扩展二叉树的先序和后序序列能唯一确定其二叉树。现给出扩展二叉树的先序序列,要求输出其中序和后序序列。

输入

输入扩展二叉树的先序序列

输出

输出其中序和后序序列

样例输入

ABD..EF..G..C..

样例输出

DBFEGAC
DFGEBCA
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
struct Tree
{
	int lchild,rchild,parent;
}t[105];
string a;
int len,k=0;
void find();
void inorder(int x);
void postorder(int x);
int main()
{
	cin>>a;
	len=a.length();
	find();
	inorder(0);
	printf("\n");
	postorder(0);
	printf("\n");
}
void find()
{
	int u=k;
	if(a[k+1]!='.')
	{
		t[u].lchild=k+1;
		k++;
		find();
	}
	else
		k++;
	if(a[k+1]!='.')
	{
		t[u].rchild=k+1;
		k++;
		find();
	}
	else
		k++;
}
void inorder(int x)
{
	if(t[x].lchild)
		inorder(t[x].lchild);
	printf("%c",a[x]);
	if(t[x].rchild)
		inorder(t[x].rchild);
}
void postorder(int x)
{
	if(t[x].lchild)
		postorder(t[x].lchild);
	if(t[x].rchild)
		postorder(t[x].rchild);
	printf("%c",a[x]);
}

猜你喜欢

转载自blog.csdn.net/acm630/article/details/81636740