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;
}