【二叉树】2255:重建二叉树

2255:重建二叉树

总时间限制: 
1000ms
内存限制: 
65536kB
描述

给定一棵二叉树的前序遍历和中序遍历的结果,求其后序遍历。

输入
输入可能有多组,以EOF结束。
每组输入包含两个字符串,分别为树的前序遍历和中序遍历。每个字符串中只包含大写字母且互不重复。
输出
对于每组输入,用一行来输出它后序遍历结果。
样例输入
DBACEGF ABCDEFG
BCAD CBAD
样例输出
ACBFGED
CDAB
提示
以英文题面为准
















比较常考的二叉树基本题型。

注意熟练掌握二叉树一些常见的操作的代码。包括Node节点数组的定义、create函数返回新节点指针、递归遍历、递归建树、

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
//二叉树节点数据结构
struct Node{
	Node *lchild;
	Node *rchild;
	char c;
	Node(){
		lchild=NULL;
		rchild=NULL;
	}
}Tree[50];
int loc;//静态数组中已经分配的节点个数
Node *create(){
	//创建新节点 返回指向新节点的指针
	Tree[loc].lchild=Tree[loc].rchild=NULL;
	return &Tree[loc++];
}
char str1[30],str2[30];//前序遍历  中序遍历
void postOrder(Node *T){
	//后序遍历
	if(T==NULL)
		return;
	//printf("%c",T->c);
	if(T->lchild!=NULL)
		postOrder(T->lchild);
	if(T->rchild!=NULL)
		postOrder(T->rchild);
	printf("%c",T->c);
}
Node *build(int s1,int e1,int s2,int e2){
	//递归还原树 返回树根节点指针
	Node *ret=create();
	ret->c=str1[s1];
	//printf("%c",ret->c);
	int rootInx;
	for(int i=s2;i<=e2;i++){
		if(str2[i]==str1[s1]){
			rootInx=i;
			break;
		}
	}
	if(rootInx!=s2){
		//有左子树
		ret->lchild=build(s1+1,s1+rootInx-s2,s2,rootInx-1);
	}
	if(rootInx!=e2){
		ret->rchild=build(s1+rootInx-s2+1,e1,rootInx+1,e2);
	}
	return ret;

}
int main(){
	while(scanf("%s",str1)!=EOF){
		scanf("%s",str2);
		int len1=strlen(str1);
		int len2=strlen(str2);
		loc=0;
		Node *root=build(0,len1-1,0,len2-1);
		postOrder(root);
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33837704/article/details/80336102