二叉树遍历问题

直奔主题
这里是原题 二叉树遍历
概括一下就是 给出了一个二叉树的前序遍历中序遍历所得到的字符 我们则要输出这个二叉树的后序遍历


首先我们要根据给出的前序遍历和中序遍历构造出这个二叉树,接下来再用一个读出后序遍历的函数即可。

首先,构造二叉树用到递归的方法
例如数据 :ABCDEFG;DCBAEFG
根据前序遍历和中序遍历的特点,A肯定为根结点,接着在中序遍历中找到A,中序遍历中A左边的即为左边树的内容,A右边则为右边树的内容,接着利用递归将问题继续拆减,得到答案。

下面给出带有注释的代码

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<math.h>
#define maxn 26+10//题目要求 可以不用理会
char s1[maxn];//前序遍历
char s2[maxn];//后序遍历
typedef struct node{//树的结构体
 	char data;
 	struct node *lchild,*rchild;
}trnode,*tree; 
tree build(int l1,int r1,int l2,int r2){//构造二叉树函数
	if(l1>r1) return NULL;
	tree root;
	root=(tree)malloc(sizeof(trnode));
	root->data=s1[l1];
	int p=l2;
	while(s2[p]!=root->data) p++;//找到中序遍历中的根结点
	root->lchild=build(l1+1,l1+p-l2,l2,p-1);//找到左子树的根节点
	root->rchild=build(l1+p-l2+1,r1,p+1,r2);//找到右子树的根节点
	return root;	
}
void back(tree root){//后序遍历
	if(root){
		back(root->lchild);
		back(root->rchild);
		printf("%c",root->data);
	}
}
int main()
{  
 	while(scanf("%s",s1)!=EOF){
	  	int len=strlen(s1);
	  	scanf("%s",s2);
	  	tree root=build(0,len-1,0,len-1);
	  	back(root);
	  	printf("\n");
	 }
 	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值