习题6-3 UVa536 Tree Recovery(树的遍历转换)

来源:互联网 发布:java守护线程作用 编辑:程序博客网 时间:2024/05/16 12:59

题意:

给出先序和中序求后序

要点:

递归完成,只要注意一下边界就可以了,水题


#include<stdio.h>#include<string.h>#include<stdlib.h>char s1[30], s2[30];char tree[30];int count;void build(int l1, int r1,int l2,int r2){if (l1 > r1) return; //空树int p = l2;while (s2[p] != s1[l1])p++;build(l1+1, l1 + p-l2,l2,p-1);build(l1+p-l2+1,r1,p+1,r2);tree[count++] = s1[l1];//后序直接放后面就行了}int main(){while (scanf("%s", s1) != EOF){scanf("%s", s2);int len = strlen(s1);count = 0;build(0, len- 1, 0,len-1);for (int i = 0; i <count; i++)printf("%c", tree[i]);printf("\n");}return 0;}


这里有一种非常精妙的算法:

利用一个全局变量n=-1,我们会发现n的值每次++后在递归过程中正好与先序遍历的根节点相同,所以可以很简单的写出程序。

#include<stdio.h>#include<stdlib.h>#include<string.h>char pre[100], in[100];int n;void tranverse(int left,int right){int i, temp;if (right <left)return;n++;//这里非常精妙,n作为根节点,按照先序遍历只要不断++即可for (i = left; i <= right;i++)if (pre[n] == in[i]){temp = i;break;}tranverse(left, temp-1);tranverse(temp + 1, right);printf("%c",in[temp]);//这里输出pre[n]不正确,因为n是全局变量,比如本来n=2时输出因为递归n会改变}int main(){while (scanf("%s%s", pre, in) != EOF){int x = strlen(pre);n = -1;tranverse(0, x - 1);printf("\n");}return 0;}



0 0