杭电1710 Binary Tree Traversals 二叉树前中后序转化

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1710

题意:输入一个二叉树的前序、中序读入,求它的后序。

                                         

思路:由前序遍历的的定义(由根先左后右)和中序遍历的定义(左中右),以及后序遍历(左右中)我们可以先求出二叉树的根,接下来递归求左二叉树的根、右二叉树的根,进而重建二叉树。

代码:

#include<iostream> 
#define N 1005 
using namespace std; 
int preorder[N]; 
int inorder[N]; 
int postorder[N]; 
void build(int n,int *s1,int *s2,int *s)  //二叉树重建 
{  
	if(n<=0)return ;  
	int p;  
	for(int i=0;i<n;i++)             //找根节点   
	if(s1[0]==s2[i])   
	{
		p=i;
	    break;   
	} 
	build(p,s1+1,s2,s);       //左二叉树的后序遍历     
	build(n-p-1,s1+p+1,s2+p+1,s+p);   //右二叉树的后序遍历  
	s[n-1]=s1[0];                  //根节点的保存 
} 
int main() 
{  
	int n;  
	while(cin>>n)  
	{   
		for(int i=0;i<n;i++)  cin>>preorder[i];   
		for(int j=0;j<n;j++)    cin>>inorder[j];   
		build(n,preorder,inorder,postorder);   
		for(int i=0;i<n-1;i++)    cout<<postorder[i]<<' ';   
		cout<<postorder[n-1]<<endl;  
	}  
	return 0; 
}

猜你喜欢

转载自blog.csdn.net/jack_jxnu/article/details/81226035
今日推荐