B - Tree Recovery
Little Valentine liked playing with binary trees very much. Her favorite game was constructing randomly looking binary trees with capital letters in the nodes. D / / B E / / A C G / / F To record her trees for future generations,she wrote down two strings for each tree: a preorder traversal (root,left subtree,right subtree) and an inorder traversal (left subtree,root,right subtree). For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG. Now,years later,looking again at the strings,she realized that reconstructing the trees was indeed possible,but only because she never had used the same letter twice in the same tree. InputThe input will contain one or more test cases. OutputFor each test case,recover Valentine‘s binary tree and print one line containing the tree‘s postorder traversal (left subtree,right subtree,root). Sample InputDBACEGF ABCDEFG Sample OutputACBFGED 题意:给你前序和中序,求后序;只要找到规律就可以,前序的第一个一定是子树的根节点,在中序的根节点左边的是根节点的左子树,一直找下去,直到不能找了输出#include<iostream> #include<stdio.h> #include<stdlib.h> #include <iomanip> #include<cmath> #include<float.h> #include<string.h> #include<algorithm> #define sf scanf #define pf printf #define mm(x,b) memset((x),(b),sizeof(x)) #include<vector> #include<queue> #include<map> #define rep(i,a,n) for (int i=a;i<n;i++) #define per(i,n) for (int i=a;i>=n;i--) typedef long long ll; const ll mod=1e9+100; const double eps=1e-8; using namespace std; const double pi=acos(-1.0); const int inf=0xfffffff; const int N=1005; char a[30],b[30]; void find(int l1,int r1,int l2,int r2) { if(l1>r1) return ; int y=l2; while(b[y]!=a[l1]) y++; find(l1+1,r1-(r2-y),l2,y-1); find(r1+1-(r2-y),r1,y+1,r2); pf("%c",a[l1]); } int main() { while(~sf("%s%s",b)) { int l=strlen(a); find(0,l-1,l-1); pf("n"); } return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |