BIT 1031 Binary Tree Traversals

题意就是给一个二叉树的前序遍历序列和中序遍历序列

9

1 2 4 7 3 5 8 9 6

4 7 2 1 8 5 9 3 6

对前序序列

1 2 4 7 3 5 8 9 6

1一定是该树的根节点

1在中序遍历中又在4 7 2之后

于是有

BIT 1031 Binary Tree Traversals_第1张图片

一层层递归下去就好了。。

#include<algorithm>
#include<iostream>
#include<cstdio>
using namespace std;
int preorder[1100];//先序
int inorder[1100];//中序
class node
{
public:
	int val;
	node *left;
	node *right;
};
void buildTree(node *tree,int prel,int prer,int inl,int inr)
{
	//此时tree里应以prel为根节点,并在i中序序列中找到prel
	tree->val=preorder[prel];
	tree->left=NULL;
	tree->right=NULL;
	int i;
	for(i=inl;i<=inr;i++)
	{
		if(inorder[i]==preorder[prel])
		{
			break;
		}
	}
	if(prel+1<=i-inl+prel&&inl<=i-1)
	{
		tree->left=new node;
		buildTree(tree->left,prel+1,i-inl+prel,inl,i-1);
	}
	if(i-inl+prel+1<=prer&&i+1<=inr)
	{
		tree->right=new node;
		buildTree(tree->right,i-inl+prel+1,prer,i+1,inr);
	}
}
void postTravel(node *p)
{
	if(p==NULL)
	{
		return;
	}
	postTravel(p->left);
	postTravel(p->right);
	printf("%d ",p->val);
}
int main()
{
	int n;
	while (~scanf("%d",&n))
	{
		for (int i = 0; i < n; i++)
		{
			scanf("%d",&preorder[i]);
		}
		for (int i = 0; i < n; i++)
		{
			scanf("%d",&inorder[i]);
		}
		node *tree;
		tree=new	node;
		buildTree(tree,0,n-1,0,n-1);
		postTravel(tree->left);//后序遍历开始
		postTravel(tree->right);
		printf("%d\n",tree->val);
	}
	return 0;
}


你可能感兴趣的:(BIT 1031 Binary Tree Traversals)