重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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)):代表二叉树的中序遍历序列。

输出:

对应每个测试案例,输出一行:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct BinaryTree
{
	int value;
	BinaryTree *left;
	BinaryTree *right;
};
BinaryTree*constructBTN(int *preorder,int *preendorder,int *midorder,int*midendorder);

BinaryTree *b_t_c(int *pre,int *mid,int len)
{
	if (pre==NULL||mid==NULL||len<0)//前序中序存在
	{
		return NULL;
	}
	return constructBTN(pre,pre+len-1,mid,mid+len-1);//前序中序的首末地址
}

BinaryTree*constructBTN(int *preorder,int *preendorder,int *midorder,int*midendorder)
{
	int root_value=preorder[0];
	BinaryTree* btree=new BinaryTree();
	btree->value=root_value;
	btree->left=NULL;
	btree->right=NULL;
	if (preorder==preendorder&&midorder==midendorder&&*preorder==*midorder)//首末地址相同 只有一个节点
	{
		return btree;
	}
	
	int *rootIndex=midorder;//取中序首地址
	
	while(*rootIndex!=root_value&&rootIndex<=midendorder)//中序中寻找根节点
	{
		rootIndex++;
	}
	if (*rootIndex!=root_value&&rootIndex!=midendorder)//没有找到
	{
		cout<<"NO"<<endl;
		return NULL;
	}
	int left_len=rootIndex-midorder;//在中序中找到根节点地址,减去中序启示节点地址
	int *left_pre_end=preorder+left_len;//前序遍历中得到左半部分
	if (left_len>0)
	{
		btree->left=constructBTN(preorder+1,left_pre_end,midorder,rootIndex-1);
		if (btree->left==NULL)
		{
			return NULL;
		}
	}
	if (left_len<preendorder-preorder)
	{
		btree->right=constructBTN(left_pre_end+1,preendorder,rootIndex+1,midendorder);
		if (btree->right==NULL)
		{
			return NULL;
		}
	}
	return btree;

}

void printbtn(BinaryTree* root)
{
	if (root!=NULL)
	{
		printbtn(root->left);
		printbtn(root->right);
		cout<<root->value<<" ";
	}
}

int main()
{
	while(1)
	{
		int num;
		cin>>num;
		int qian[100];
		int zhong[100];
		memset(qian,0,sizeof(qian));
		memset(zhong,0,sizeof(zhong));
		int value;
		for (int i=0;i<num;i++)
		{
			cin>>qian[i];
		}
		for (int i=0;i<num;i++)
		{
			cin>>zhong[i];
		}
		BinaryTree *proot=b_t_c(qian,zhong,num);
		printbtn(proot);
	}
	return 0;
}

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

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

样例输入:
8
1 2 4 7 3 5 6 8
4 7 2 1 5 3 8 6
8
1 2 4 7 3 5 6 8
4 1 2 7 5 3 8 6
样例输出:
7 4 2 5 8 6 3 1 
No



发布了35 篇原创文章 · 获赞 9 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章