Java教程

【模板】【建树】前序+中序 后序+中序

本文主要是介绍【模板】【建树】前序+中序 后序+中序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

建树:已知一棵树的 前序+中序后序+中序 即可以递归的建立一棵树。

#include<iostream>
#include<cstdlib>
using namespace std;

const int N = 100;
int n;
int mind[N], prio[N], post[N];

struct Tree {
	int data;
	Tree* lchild, * rchild;
};

//先序 + 中序
Tree* CreateByPrio(int x,int y,int z)
{
	if (z == 0) return NULL;
	Tree* root = new Tree;
	root->data = prio[y];
	int len;
	for (int i = x; i < x + z; i++)
	{
		if (mind[i] == prio[y]) {
			len = i - x;
			break;
		}
	}
	root->lchild = CreateByPrio(x, y + 1, len);
	root->rchild = CreateByPrio(x + len + 1, y + len + 1, z - len - 1);
	return root;
}

//后序 + 中序
Tree* CreateByPost(int x, int y, int z)
{
	if (z == 0) return NULL;
	Tree* root = new Tree;
	root->data = post[y + z - 1];
	int len;
	for (int i = x; i < x + z; i++)
	{
		if (mind[i] == post[y + x - 1])
		{
			len = i - x;
			break;
		}
	}
	root->lchild = CreateByPost(x, y, len);
	root->rchild = CreateByPost(x + len + 1, y + len, z - len - 1);
	return root;
}

int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> mind[i];
	for (int i = 0; i < n; i++)
		cin >> prio[i];
	return 0;
}

这篇关于【模板】【建树】前序+中序 后序+中序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!