【C++】满二叉树问题
/* 给出一棵满二叉树的先序遍历,有两种节点:字母节点(A-Z,无重复)和空节点(#)。要求这个树的中序遍历。输出中序遍历时不需要输出#。 满二叉树的层数n满足1<=n<=5。 Sample Input: ABC#D#E Sample Output: CBADE */ #include<cstdio> #include<cmath> #include<cstring> #include<iostream> using namespace std; const int M=1024; char data[M]; int layer; struct node { char data; struct node *l; struct node *r; }; void build(node * & t,int l) { if(l>layer) return ; int i=0; while(data[i]=='\0') i++; char tc=data[i]; //cout<<i<<endl<<tc<<endl; data[i]='\0'; if(tc=='#') { t=NULL; return ; } t=new node(); t->data=tc; build(t->l,l+1); build(t->r,l+1); } void display(node *t) { if(t==NULL) return ; display(t->l); printf("%c",t->data); display(t->r); } int main() { /* printf("%d\n",(int)(log(8)/log(2))); printf("%f\n",(log(7)/log(2))); */ memset(data,'\0',sizeof(data)); while(scanf("%s",&data)) { //printf("%s\n",data); int n=strlen(data)+1; /* if(log(n)/log(2)>(int)(log(n)/log(2))) layer=(int)(log(n)/log(2))+1; else*/ layer=(int)(log(n)/log(2)); //printf("%d\n",layer); node *tree; build(tree,1); display(tree); } return 0; }
tz@HZAU
2019/3/13