POJ T2255 Tree Recovery
题解:
在纸上模拟建树过程,找出下标之间的关系,推出递推公式即可
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int MAXN = 27;
void build(int n,char *pre,char *in){
if(n == 0) return;
int pos = strchr(in,pre[0]) - in;
build(pos,pre+1,in);
printf("%c",pre[0]);
build(n-pos-1,pre+pos+1,in+pos+1);
}
int main(){
char pre[MAXN],in[MAXN];
while(~scanf("%s%s",pre,in)){
int n = strlen(pre);
build(n,pre,in);
printf("\n");
}
return 0;
}
本文介绍了一种通过先序和中序遍历构建二叉树的算法,并提供了完整的C++实现代码。通过递归的方式找到每个节点的位置,最终打印出先序遍历的结果。

5298

被折叠的 条评论
为什么被折叠?



