Tree Recovery 2
Tree Recovery 2
h> #include <cstring> #include <ctype.h> #include <stdio.h> #define MAX 26 using namespace std; class NODE { private: char data; NODE *leftchild; NODE *rightchild; public: void setvalue(char temp) { data=temp; } char getvalue() { return data; } void setleftchild(NODE *temp) { leftchild=temp; } NODE* getleftchild() { return leftchild; } void setrightchild(NODE *temp) { rightchild=temp; } NODE* getrightchild() { return rightchild; } }; class BUILDTREE { private: int preindex;
int inindex; NODE *tree_node; public: BUILDTREE() { preindex=inindex=0; tree_node=NULL; } NODE* buildtree(char in[], char pre[], int start, int end) { if(start>end) { return NULL; } tree_node=new NODE(); tree_node->setvalue(pre[preindex++]); tree_node->setleftchild(NULL); tree_node->setrightchild(NULL); if(start==end) { return tree_node; } inindex=search(in,start,end,tree_node->getvalue()); tree_node->setleftchild(buildtree(in,pre,start,inindex-1)); tree_node->setrightchild(buildtree(in,pre,inindex+1,end)); return tree_node; } int search(char in[], int start, int end, char value) { for(int i=start;i<end;i++) { if(in[i]==value) { return i; } } return 0; } void postorder(NODE *temp) { if(temp==NULL) { return ; } postorder(temp->getleftchild()); postorder(temp->getrightchild()); cout<<temp->getvalue(); } };
int _tmain(int argc, _TCHAR* argv[]) { char in[MAX]; char preorder[MAX]; int times,i=1,len; NODE *root; BUILDTREE B; cin>>times; cin.ignore(); while(i<=times) { system("cls"); fgets(preorder,sizeof(preorder),stdin); fgets(in,sizeof(in),stdin); preorder[strlen(preorder)-1]='\0'; in[strlen(in)-1]='\0'; len=strlen(preorder); system("cls"); for(int j=0;j<len;j++) { cout<<preorder[j]; } cout<<" "; for(int j=0;j<len;j++) { cout<<in[j]; } getche(); system("cls"); root=B.buildtree(in,preorder,0,len-1); B.postorder(root); i++; } cout<<"\n\n"; return 0; }