根据二叉树前序序列和中序序列还原二叉树,并输出后序遍历序列

code:

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <stdexcept>
#include<algorithm>
#include<stack>
#include<queue>
#include<functional>

struct Node {
	Node*lchild;
	Node*rchild;
	char data;
}Tree[50];
int loc;
// 创建一个节点
Node*create()
{
	Tree[loc].lchild = Tree[loc].rchild = NULL;
	return &Tree[loc++];
}
char str1[30], str2[30];
// 后续遍历
void postOrder(Node*T)
{
	if (T->lchild != NULL)
		postOrder(T->lchild);
	if (T->rchild != NULL)
		postOrder(T->rchild);
	printf("%c", T->data);
}
// 中序遍历
void midOrder(Node*T)
{
	if (T->lchild != NULL)
		midOrder(T->lchild);
	printf("%c", T->data);
	if (T->rchild != NULL)
		midOrder(T->rchild);
}
// 前序遍历
void preOrder(Node*T)
{
	printf("%c", T->data);
	if (T->lchild != NULL)
		preOrder(T->lchild);
	if (T->rchild != NULL)
		preOrder(T->rchild);
}
// 根据前序和中序序列还原二叉树
// 返回还原的二叉树的根节点
Node*build(int s1, int e1, int s2, int e2)
{
	// 创建根节点,申请空间
	Node*root = create();
	root->data = str1[s1];

	int rootIdx;
	// 前序遍历的当前节点在中序遍历中的位置
	for (int i = s2; i <= e2; i++)
	{
		if (str2[i] == str1[s1])
		{
			rootIdx = i;
			break;
		}
	}
	// 中序序列中的当前节点的左子树非空
	if (rootIdx != s2)
		root->lchild = build(s1 + 1, s1 + (rootIdx - s2), s2, rootIdx - 1);
	// 中序序列中的当前节点的右子树非空
	if (rootIdx != e2)
		root->rchild = build(s1 + (rootIdx - s2) + 1, e1, rootIdx + 1, e2);
	return root;
}

void get_postOrder()
{
	int x;
	scanf_s("%d", &x);
	while (x)
	{
		std::cin >> str1;
		std::cin >> str2;
		loc = 0;
		int l1 = strlen(str1);
		int l2 = strlen(str2);
		Node*T = build2(0, l1 - 1, 0, l2 - 1);
		preOrder(T);
		printf("\n");
		scanf_s("%d", &x);
	}
}

int main(void)
{
	get_postOrder();
	

	system("pause");
    return 0;
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值