清华数据结构真二叉树重建AC100

该题难点主要在于如何判断哪边是左子树,哪边是右子树

假设先序序列为a[maxn],后序序列为b[maxn]

对于类似数据为

13
1 2 4 6 10 9 12 13 7 11 8 5 3
10 12 13 9 6 11 8 7 4 5 2 3 1

对于左子树,记b[j]=9,b[i]=12。我们可以看到i<j。因此,当在a进行遍历时,不能再将其认为是左子树,得将其认为是右子树的条件是,i>j||j==0。因为右子树的坐标,总是在左子树后面(后序遍历,左右中),越左的左子树,越先被读取,故坐标值越小。那么当存在更小的坐标值时,则说明还可以向左。否则,说明是创建右子树了

对于右子树,如果要停止,则在创建完数之后,j-i=1。因此,右子树停止创建的条件是j-i<=1;

100分代码如下

#pragma warning(disable:4996)
#include<stdio.h>
using namespace std;
#define maxn 4000000
int a[maxn], b[maxn], c[maxn], d[maxn],n;
struct binnode {
	int data;
	binnode*lc, *rc, *parent;
	binnode() :data(0), lc(NULL), rc(NULL), parent(NULL) {}
	binnode(int e, binnode*p3 = NULL, binnode*p1 = NULL, binnode*p2 = NULL) :data(e), parent(p3), lc(p1), rc(p2) {}
};
class bintree {
private:
	binnode * _root;
	int _size;
public:
	bintree() :_size(0), _root(NULL) {}
	int size() { return _size; }
	binnode*root() { return _root; }
	binnode*insertaslc(binnode*p, int const&e);
	binnode*insertasrc(binnode*p, int const&e);
	binnode*insertasroot(int const&e);
};
binnode* bintree::insertaslc(binnode*p, int const&e)
{
	binnode*p1 = new binnode(e, p);
	p->lc = p1;
	_size++;
	return p1;
}
binnode* bintree::insertasrc(binnode*p, int const&e)
{
	binnode*p1 = new binnode(e);
	p->rc = p1;
	_size++;
	return p1;
}
binnode* bintree::insertasroot(int const&e)
{
	_root = new binnode(e);
	_size = 1;
	return _root;
}
bintree tree;
void creatright_tree(binnode*p, int lo3, int lo);
//lo2,lo3这些都是坐标
void creatleft_tree(binnode*p, int lo2)
{

	auto t = tree.insertaslc(p, a[lo2]);
	auto lo3 = c[a[lo2]];
	if (lo3>0&&c[a[lo2]]>c[a[lo2+1]])//否则a[lo2+1]是右子树
	{
		creatleft_tree(t, ++lo2);
		creatright_tree(t, --lo3,lo2);
	}
}
void creatright_tree(binnode*p, int lo3,int lo)
{
	auto t = tree.insertasrc(p, b[lo3]);
	auto lo2 = d[b[lo3]];
	if (lo3-c[a[lo]]>1)
	{
		creatleft_tree(t, ++lo2);
		creatright_tree(t, --lo3,lo2);
	}
}
void midtral(binnode*p)
{
	if (!p)return;
	midtral(p->lc);
	if(p->data!=a[n-1])printf("%d ", p->data);
	else printf("%d\n",p->data);
	midtral(p->rc);
}
int main()
{
	int lo1 = 0, lo2 = 0, lo3 = 0;//lo1是根的开始,lo2是左子树的开始,lo3是右子树的开始
#ifndef _OJ_
	freopen("createtree.txt", "r", stdin);
	// freopen("trainout.txt", "w", stdout);
#endif
	scanf("%d", &n);
	for (auto i = 0; i<n; i++)scanf("%d", &a[i]);
	for (auto i = 0; i<n; i++)scanf("%d", &b[i]);
	//使得可以根据值找到对应的坐标
	if(n<2){printf("%d\n", 1);return 0;}
	else{
	for (auto i = 1; i<n + 1; i++)c[b[i]] = i;//c是b的坐标
	for (auto i = 1; i<n + 1; i++)d[a[i]] = i;//d是a的坐标
	// for(auto i=1;i<n+1;i++)printf("%d\n",d[i]);
	auto root = tree.insertasroot(a[0]);
	creatleft_tree(root, 1);
	creatright_tree(root, --c[a[0]],1);
	midtral(root);}
	// auto right=b[n-2];
	// auto left=a[1];
}

猜你喜欢

转载自blog.csdn.net/hgtjcxy/article/details/80471394