2018-3-12
在牛客网上提交了一下,贼坑,每一行最后一个元素后有空格,并且输入可能有相同的元素。
#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<algorithm> using namespace std; struct Node { int num; Node *lson,*rson; } node[105]; int size,n; Node *create(int num) { node[size].num=num; node[size].lson=node[size].rson=NULL; return &node[size++]; } Node *insert(Node *rt,int num) { if(rt==NULL) { rt=create(num); return rt; } if(rt->num==num) return rt; else if(rt->num>num) rt->lson=insert(rt->lson,num); else rt->rson=insert(rt->rson,num); return rt; } void preOrder(Node *rt) { if(rt==NULL) return; printf("%d ",rt->num); preOrder(rt->lson); preOrder(rt->rson); } void inOrder(Node *rt) { if(rt==NULL) return; inOrder(rt->lson); printf("%d ",rt->num); inOrder(rt->rson); } void postOrder(Node *rt) { if(rt==NULL) return; postOrder(rt->lson); postOrder(rt->rson); printf("%d ",rt->num); } int main() { while(scanf("%d",&n)!=EOF) { size=0; Node *rt=NULL; for(int i=0;i<n;i++) { int tmp; scanf("%d",&tmp); rt=insert(rt,tmp); } preOrder(rt); printf("\n"); inOrder(rt); printf("\n"); postOrder(rt); printf("\n"); } return 0; }
思路简单,但是实现时有的地方需要注意,
1) insert(Node *rt,int num)的传参,指针做形参是地址传递,可以达到修改形参所指地址内容的目的,但这个形参的值即地址值不会发生变化,最开始Insert是这样写的
void insert(Node *rt,int num) { if(rt==NULL) { //cout<<"**"<<endl; rt=create(num); return rt; } if(num<rt->num) insert(rt->lson,num); else if(num>rt->num) insert(rt->rson,num); }
最开始不觉得有什么不对,但是发现insert完过后,rt==NULL;分析应该是,指针做参数可以改变rt指向的单元的内容,但如同一般变量的传参,函数体内对形参的操作不会改变传入的实参的值
#include<iostream> #include<cstdio> using namespace std; struct Node { Node *lson,*rson; int num; } node[105]; int cntn; Node *create(int num) { node[cntn].lson=node[cntn].rson=NULL; node[cntn].num=num; return &node[cntn++]; } int cnt,n; void preOrder(Node *rt) { if(rt==NULL) return; //cout<<"*"<<endl; printf("%d",rt->num); if(++cnt==n) printf("\n"); else printf(" "); preOrder(rt->lson); preOrder(rt->rson); } void inOrder(Node *rt) { if(rt==NULL) return; //cout<<"*"<<endl; inOrder(rt->lson); printf("%d",rt->num); if(++cnt==n) printf("\n"); else printf(" "); inOrder(rt->rson); } void postOrder(Node *rt) { if(rt==NULL) return; //cout<<"*"<<endl; postOrder(rt->lson); postOrder(rt->rson); printf("%d",rt->num); if(++cnt==n) printf("\n"); else printf(" "); } Node *insert(Node *rt,int num) { if(rt==NULL) { rt=create(num); return rt; } if(num<rt->num) rt->lson=insert(rt->lson,num); else if(num>rt->num) rt->rson=insert(rt->rson,num); } int main() { while(scanf("%d",&n)!=EOF) { cntn=0; Node *rt=NULL; for(int i=0; i<n; i++) { int num; scanf("%d",&num); rt=insert(rt,num); } cnt=0; preOrder(rt); cnt=0; inOrder(rt); cnt=0; postOrder(rt); } return 0; }