思路简单,但是实现时有的地方需要注意,
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; }