Tree Recovery

Tree Recovery

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
进军二叉树啦!之前也在《大话数据结构》一书中了解了一些,这道题考二叉树的重建,知道了前序遍历与中序遍历的结果,从而构建二叉树并且输出后序遍历的结果,大致思路使用递归,递归的最小单位呢?就是我们知道我们每遇到前序遍历结果的一个字母都会是一个根,然后我们在中序遍历的结果中寻找这个根,而根据中序遍历的特点知道根左侧为其左子树,右侧为其右子树,以此递归就能知道整个树的结构了,最后根据后序遍历的要求输出即可!

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char s[30], t[30];
struct node {//创建节点结构体 
	char n;
	node* subl, * subr;//左右子树 
};
//使用插入操作构建新树 
node* insert(char* s, char* t, int l) {
	if (l <= 0) return NULL;
	node* root = new node;//创建新节点 
	root->n = *s;//s 的首字符是当前树的根(前序遍历的特点) 
	char* p = t;//在中序遍历的字符串中寻找上面的根 
	while (*p != *s) p++;
	int length = p - t;//求左右子树的长度,以进行递归 
	root->subl = insert(s + 1, t, length);
	root->subr = insert(s + length + 1, p + 1, l - length - 1);
	return root;
}

//后序遍历打印 
void print(node* root) {
	if (root == NULL) return;
	print(root->subl);
	print(root->subr);
	cout << root->n;
}

//前序遍历打印 
/*void print(node*root){
	if(root=NULL);
	cout<<root->n;
	print(root->subl);
	print(root->subr);
}*/

//中序遍历打印 
/*void print(node*root){
	if(root=NULL);
	print(root->subl);
	cout<<root->n;
	print(root->subr);
}*/

int main() {
	while (scanf("%s%s", s, t) != EOF) {
		//注意!!输入字符串时不用加 & 了!! 
		node* root = new node;
		int l = strlen(s);
		root = insert(s, t, l);
		print(root);
		cout << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值