已知中序和后序建树

原题目是给你中序遍历和后序遍历,让你求出分层遍历的结果。

这是根据中序遍历和后序遍历,进行建树,然后各种遍历结果就很容易求出了。

build(int inl, int inr, int pol, int por, Node* &root)

inl 表示建树时中序遍历的左边界限制, inr 表示建树时右边界的限制,pol,por表示后序遍历左右边界的限制,Node* &root 是当前根节点的引用,求出不必返回。


#include<iostream>
#include<stdio.h>
#include<vector>
#include<cstring>
#include<string>
#include<queue>
#include<math.h>
#include<stack>

#include<algorithm>

using namespace std;

const int inf = 0x3f3f3f3f;
int num[1000000];
int cou;
class Node
{
public:
	int data;
	Node(int d) :data(d), left(NULL), right(NULL) {}
	Node *left;
	Node *right;

	void ce(int pos)
	{
		num[pos] = data;
		cou++;
		if (left != NULL)
			left->ce(pos * 2);
		if (right != NULL)
			right->ce(pos * 2 + 1);
	}
};
class Tree
{
public:
	Node *root;
	Tree() :root(NULL) {}
};
int inorder[31];
int postorder[31];
queue<int>q;

void build(int inl, int inr, int pol, int por, Node* &root)
{
	root = new Node(postorder[por]);
	int mid;
	for (int i = inl; i <= inr; ++i)
	{
		if (inorder[i] == postorder[por])
		{
			mid = i;
			break;
		}
	}
	if (mid - inl>0)
		build(inl, mid - 1, pol, pol + mid - inl - 1, root->left);
	if (inr - mid>0)
		build(mid + 1, inr, pol + mid - inl, por - 1, root->right);
}

int main()
{
	cou = 0;
	memset(num, 0x3f, sizeof(num));
	int n;
	cin >> n;
	for (int i = 1; i <= n; ++i)
	{
		cin >> postorder[i];
	}
	for (int i = 1; i <= n; ++i)
	{
		cin >> inorder[i];
	}

	Tree t;
	build(1, n, 1, n, t.root);
	t.root->ce(1);
	int add = 1;
	for (int i = 1; i<100000; ++i)
	{
		if (num[i] != 0x3f3f3f3f)
		{
			if (add != cou)
				cout << num[i] << ' ';
			else
				cout << num[i];
			add++;
		}
	}
	return 0;
}



















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值