POJ 2255 Tree Recovery(算法竞赛入门经典,二叉树遍历,水题)

算法竞赛入门经典177页,二叉树遍历,水题
题目意思:
给出先序和中序,求后序

本题要点:
1、 一个二叉树的先序和中序,确定一颗唯一的二叉树。
2、写一个递归,由先序和中序建立一颗二叉树
3、再写一个递归,后序遍历二叉树,打印每一节点。

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MaxN = 30;
char pre[MaxN], mid[MaxN];

struct node
{
	char ch;
	node* left;
	node* right;
};

node* build(int l1, int r1, int l2, int r2)
{
	if(l1 > r1)	
		return NULL;
	node* root = new node;
	root->ch = pre[l1];
	int k;
	for(k = l2; k <= r2; ++k)
	{
		if(mid[k] == pre[l1])
		{
			break;
		}
	}
	root->left = build(l1 + 1, k - l2 + l1, l2, k - 1);
	root->right = build(k - l2 + l1 + 1, r1, k + 1, r2);
	return root;
}

void postOrder(node* root)
{	
	if(root)
	{
		postOrder(root->left);
		postOrder(root->right);
		printf("%c", root->ch);
	}
}

void destroy(node* root)
{
	if(root)
	{
		destroy(root->left);
		destroy(root->right);
		delete root;
	}
}

int main()
{
	while(scanf("%s", pre) != EOF)
	{
		scanf("%s", mid);
		int len1 = strlen(pre), len2 = strlen(mid);
		node* root = build(0, len1 - 1, 0, len2 - 1);
		postOrder(root);
		printf("\n");
		destroy(root);
	}
	return 0;
}

/*
DBACEGF ABCDEFG
BCAD CBAD
*/

/*
ACBFGED
CDAB
*/

猜你喜欢

转载自blog.csdn.net/qq_38232157/article/details/108359756
今日推荐