二叉树的应用:前中序转后序

  • 基本理论
    1.二叉树结点结构体:左右孩子指针&data
struct BTNode()
{
	BTNode *lchild;
	BTNode *rchild;
	/**
	其他信息
	**/
};

2.递归遍历方法(eg.中序遍历)

void inOrder(BTNode *Tree)
{
	if(Tree->lchild!=NULL)
		inOrder(Tree->lchild);
	/**
	遍历当前结点
	**/
	if(Tree->rchild!=NULL)
		inOrder(Tree->rchild);
	return;
}
  • 例1、给出二叉树前中序,输出后序。
    在这里插入图片描述
    思路:由前中序建立一棵二叉树,在读出后序。
    结构体:
struct Node{
	BTree *lchild;
	BTree *rchild;
	char c;
};

解题:

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;

struct Node{
	Node *lchild;
	Node *rchild;
	char c;
}Tree[50];//静态内存分配数组
int loc=0;//静态数组中已分配的数组个数
//申请一个结点空间,返回指向他的指针
Node *creat()
{
	Tree[loc].lchild=Tree[loc].rchild=NULL;
	return &Tree[loc++];
}
//保存前中序遍历字符
char str1[50],str2[50];
//后序遍历
void postOrder(Node *T)
{
	if(T->lchild!=NULL)
		postOrder(T->lchild);
	if(T->rchild!=NULL)
		postOrder(T->rchild);
	cout<<T->c;
	return;
}
//由前中序建立一棵二叉树,返回根节点
//前序遍历结果为由srt1[s1]到srt2[e1]
//中序遍历结果为由srt2[s2]到srt2[e2]
Node *build(int s1,int e1,int s2,int e2)
{
	Node* ret=creat();//为树根结点申请空间
	ret->c=str1[s1];//树根结点为前序遍历第一个字符
	int rootIdx;//树根结点在中序遍历中的位置
	//查找树根结点在中序遍历中的位置
	for(int i=s2;i<=e2;i++)
	{
		if(str2[i]==ret->c)
		{
			rootIdx=i;
			break;
		}
	}
	//递归还原左子树
	if(rootIdx!=s2)//左子树不为空
	{
		ret->lchild=build(s1+1,s1+(rootIdx-s2),s2,rootIdx-1);
	}
	//递归还原右子树
	if(rootIdx!=e2)//右子树不为空
	{
		ret->rchild=build(s1+(rootIdx-s2)+1,e1,rootIdx+1,e2);
	}
	return ret;//返回根节点指针
}
int main(){
	cin>>str1>>str2;
	int len1=strlen(str1),len2=strlen(str2);
	//还原整棵树,根节点指针保存在T中
	Node *T=build(0,len1-1,0,len2-1);
	//后序遍历
	postOrder(T);
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值