noj 18 根据二叉树的前序和中序遍历结果重建二叉树

noj 18 根据二叉树的前序和中序遍历结果重建二叉树

题目描述
重构的原理:
(参考链接:https://blog.csdn.net/okiwilldoit/article/details/78355872)
在这里插入图片描述
下面放重建函数的递归代码

void InitNode(p_BTNode* p) {
	*p = (p_BTNode)malloc(sizeof(BTNode));
	(*p)->Lchild = (*p)->Rchild = NULL;
}

p_BTNode Rebuild(char* str_pre, char* str_in) {//分别是前序字符串,中序字符串,右字串长度
	char c1 = str_pre[0], c2 = str_in[0];
	char s1[100] = { 0 }, s2[100] = { 0 };
	int Lcounter = 0, Rcounter = 0;
	while (c2 != c1) {//这一个循环有两个作用,统计左串长度以及生成新的左串
		s1[Lcounter] = c2;
		c2 = str_in[++Lcounter];
	}
	c2 = str_in[Lcounter + 1];
	while (c2 != 0) {//同上
		s2[Rcounter] = c2;
		c2 = str_in[++Rcounter + Lcounter + 1];
	}
	p_BTNode p;
	InitNode(&p);
	p->data = c1;
	if (Lcounter == 0) {
		p->Lchild = NULL;//递归出口
	}
	else {
		p->Lchild = Rebuild(str_pre + 1, s1);
	}
	if (Rcounter == 0) {
		p->Rchild = NULL;//递归出口
	}
	else {
		p->Rchild = Rebuild(str_pre + Lcounter + 1, s2);
	}
	return p;
}

整体代码:

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

typedef struct Node {
	char data;
	struct Node* Lchild;
	struct Node* Rchild;
}BTNode, * p_BTNode;

void InitNode(p_BTNode* p) {
	*p = (p_BTNode)malloc(sizeof(BTNode));
	(*p)->Lchild = (*p)->Rchild = NULL;
}

p_BTNode Rebuild(char* str_pre, char* str_in) {//分别是前序字符串,中序字符串,右字串长度
	char c1 = str_pre[0], c2 = str_in[0];
	char s1[100] = { 0 }, s2[100] = { 0 };
	int Lcounter = 0, Rcounter = 0;
	while (c2 != c1) {//这一个循环有两个作用,统计左串长度以及生成新的左串
		s1[Lcounter] = c2;
		c2 = str_in[++Lcounter];
	}
	c2 = str_in[Lcounter + 1];
	while (c2 != 0) {//同上
		s2[Rcounter] = c2;
		c2 = str_in[++Rcounter + Lcounter + 1];
	}
	p_BTNode p;
	InitNode(&p);
	p->data = c1;
	if (Lcounter == 0) {
		p->Lchild = NULL;//递归出口
	}
	else {
		p->Lchild = Rebuild(str_pre + 1, s1);
	}
	if (Rcounter == 0) {
		p->Rchild = NULL;//递归出口
	}
	else {
		p->Rchild = Rebuild(str_pre + Lcounter + 1, s2);
	}
	return p;
}

void PostOrder(p_BTNode root) {
	if (root->Lchild)
		PostOrder(root->Lchild);
	if (root->Rchild)
		PostOrder(root->Rchild);
	printf("%c", root->data);
}

int main() {
	p_BTNode p;
	InitNode(&p);
	char s1[100] = { 0 }, s2[100] = { 0 };
	scanf("%s", s1);
	scanf("%s", s2);
	p = Rebuild(s1, s2);
	PostOrder(p);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值