已知一个二叉树的中序序列和后序序列,写一个建立该二叉树的二叉链表存储结构的程序(二叉树建立的C语言实现)

已知一个二叉树的中序序列和后序序列,写一个建立该二叉树的二叉链表存储结构的程序。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

//二叉树的存储表示 
typedef char TElemType;
typedef struct BiTNode {
	TElemType data;
	struct BiTNode *lchild, *rchild;	//左右孩子指针 
}BiTNode, *BiTree;


//inorder和postorder是二叉树的中序序列和后序序列
//lowin,highin是中序序列第一和最后结点的下标
//lowpost,highpost 是后序序列第一和最后结点的下标
//返回:二叉树的根结点指针 
BiTree CreateBitree(TElemType inorder[], TElemType postorder[], int lowin, int highin, int lowpost, int highpost)
{
	BiTree t = (BiTree)malloc(sizeof(BiTNode));
	t->data = postorder[highpost];//对于后序遍历,最后一个肯定是根节点
	t->lchild = t->rchild = NULL;//初始化根节点的左右孩子节点
	for (int pos = lowin; pos <= highin; pos++) {
		if (inorder[pos] == postorder[highpost]) {
			if(pos!=lowin) 
				t->lchild = CreateBitree(inorder, postorder, lowin, pos-1, lowpost, lowpost + pos - lowin-1);//左二叉树建立
			if(pos!=highin) 
				t->rchild = CreateBitree(inorder, postorder, pos + 1, highin, highpost-pos+lowin, highpost - 1);//右二叉树建立
			break;
		}
	}
	
	return t;
}

//按前序递归遍历二叉树 
void preorder(BiTree t)
{
	if (t)
	{
		printf("%c ", t->data);
		if (t->lchild)
			preorder(t->lchild);
		if (t->rchild)
			preorder(t->rchild);
	}
}

int main()
{
	TElemType in[] = "DBEAFCG";//中序 
	TElemType post[] = "DEBFGCA";	//后序 
	BiTree t;
	t = CreateBitree(in, post, 0, strlen(in) - 1, 0, strlen(post) - 1);
	preorder(t);
	system("pause");
}
  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值