依据前序和中序列 重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。如果输入的前序遍历和中序遍历的结果中都不含反复的数字。比如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}。则重建二叉树并输出它的后序遍历序列。

输入:

输入可能包括多个測试例子。对于每一个測试案例,

输入的第一行为一个整数n(1<=n<=1000):代表二叉树的节点个数。

输入的第二行包含n个整数(当中每一个元素a的范围为(1<=a<=1000)):代表二叉树的前序遍历序列。

输入的第三行包含n个整数(当中每一个元素a的范围为(1<=a<=1000)):代表二叉树的中序遍历序列。

输出:

相应每一个測试案例。输出一行:

假设题目中所给的前序和中序遍历序列能构成一棵二叉树,则输出n个整数,代表二叉树的后序遍历序列。每一个元素后面都有空格。

假设题目中所给的前序和中序遍历序列不能构成一棵二叉树,则输出”No”。

例子输入:
81 2 4 7 3 5 6 84 7 2 1 5 3 8 681 2 4 7 3 5 6 84 1 2 7 5 3 8 6
例子输出:
7 4 2 5 8 6 3 1 No
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <stack>
#include <vector>
#include <math.h>


using namespace std;

struct node{
	node *left;
	node *right;
	int val;
	node()
	{
		right=NULL;
		left=NULL;
		val=0;
	};
} ;
node *creat(int preorder[],int len,int inorder[])
{
	if(len<=0)
	return NULL;
	node *root=NULL;
	int val=preorder[0];
	int i=0;
	for(;i<len;i++)
	{
		if(inorder[i]==val)
		{
			break;
		}
	}
	if(i>=len)
	{
		return NULL;
	}
	else
	{   
		root=new node(); 
		root->val=val;
		root->left=creat(&preorder[1],i,inorder);
		root->right=creat(&preorder[i+1],len-i-1,&inorder[i+1]);
		return root;
	}
	return NULL;
}
void preorder(node *root)
{
	if(root)
	{
		cout<<root->val<<endl;
		preorder(root->left);
		preorder(root->right);
	}
}
int main()
{ 
 int a[8]={1,2,4,7,3,5,6,8};
 int b[8]={4,7,2,1,5,3,8,6};
 node *root=creat(a,8,b);
 preorder(root);   
}


原文地址:https://www.cnblogs.com/mengfanrong/p/5147866.html