根据树的两种遍历序列求第三种遍历序列

来源:互联网 发布:淘宝市场行情 编辑:程序博客网 时间:2024/05/23 14:54

只知道先序序列和后序序列是无法求出唯一的树,所以不做讨论。

注意内存的释放,这里还没做- -

#include <iostream>#include <cstdio>#include <cstring>using namespace std;struct node{char c;node *l, *r;node(){l = NULL, r = NULL;}}root1,root2;char first[100], mid[100], last[100];void preSearch(node *root)//先序遍历树{if(root != NULL){printf("%c", root->c);preSearch(root->l);preSearch(root->r);}return ;}void midSearch(node *root)//中序遍历树{if(root != NULL){midSearch(root->l);printf("%c", root->c);midSearch(root->r);}return ;}void postSearch(node *root)//后序遍历树{if(root != NULL){postSearch(root->l);postSearch(root->r);printf("%c", root->c);}return ;}void BuildTreeFromPreAndMid(node *root, int ll, int lr, int len, int &now)//根据中序和先序求树{root->c =*(first + now);int pos = (int)(strchr(mid, *(first + now)) - mid);now++;if(now >= len)return ;if(pos - 1 >= ll){node *t = new node;root->l = t;BuildTreeFromPreAndMid(root->l, ll, pos - 1, len, now);}if(pos + 1 <= lr){node *t = new node;root->r = t;BuildTreeFromPreAndMid(root->r, pos + 1, lr, len, now);}}void BuildTreeFromPostAndMid(node *root, int ll, int lr, int len, int &now)//根据中序和后序求树{root->c =*(last + now);int pos = (int)(strchr(mid, *(last + now)) - mid);now--;if(now < 0)return ;if(pos + 1 <= lr){node *t = new node;root->r = t;BuildTreeFromPostAndMid(root->r, pos + 1, lr, len, now);}if(pos - 1 >= ll){node *t = new node;root->l = t;BuildTreeFromPostAndMid(root->l, ll, pos - 1, len, now);}}int main(){gets(first);gets(mid);gets(last);int now = 0;BuildTreeFromPreAndMid(&root1, 0, strlen(first) - 1, strlen(first), now);int now2 = strlen(last);BuildTreeFromPostAndMid(&root2, 0, strlen(last) - 1, strlen(last), now2);postSearch(&root1);preSearch(&root2);return 0;}