Tree Recovery
/*已知二叉树的先序遍历序列和中序遍历序列,输出它的后序遍历序列. 输入:DBAFCEG FABCDEG 输出:FACBGED */ #include<iostream> #include<string> using namespace std; #define NULL 0 typedef char TElementType; typedef struct BiTNode{ TElementType data; struct BiTNode*lchild,*rchild; }BiTNode,*BiTree; void CreateTree(BiTree &T,string pre,string ino) { int pos,len; len=pre.size(); if(len==0) T=NULL; //树为空 else { pos=ino.find(pre[0]); if(pos==-1) T=NULL; else { T=new BiTNode; T->data=pre[0]; if(pos==0) T->lchild=NULL; else CreateTree(T->lchild,pre.substr(1,pos),ino.substr(0,pos)); if(pos==len-1) T->rchild=NULL; else CreateTree(T->rchild,pre.substr(pos+1),ino.substr(pos+1)); } } }//CreateTree void print(BiTree T) //后续遍历 { if(T==NULL) return; print(T->lchild); print(T->rchild); cout<<T->data; }//print int main() { string s1,s2; BiTree T; cin>>s1>>s2; int n=s1.size(); int ps=0,js=0; CreateTree(T,s1,s2); print(T); return 0; }
我是一名在校大学生,热爱编程,虽然起步晚了些,但我会努力的。呵呵!
数据结构 算法