The idea is simple, but the realization of some places need to pay attention to,
1) Insert (Node *rt,int num) of the parameter, the pointer is the address of the parameter is passed, you can modify the address of the parameter refers to the purpose of the content, but the parameter value is the address value will not change, the first insert is written like this
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);}
At first do not think there is anything wrong, but found that after the insert, rt==null; the analysis should be that the pointer does the parameter can change the contents of the unit that the RT points to, but as a general variable, the function body does not change the value of the arguments passed in the action
#include <iostream>#include<cstdio>using namespacestd;structnode{Node*lson,*Rson; intnum;} node[ the];intCntn; Node*create (intnum) {Node[cntn].lson=node[cntn].rson=NULL; Node[cntn].num=num; return&node[cntn++];}intCnt,n;voidPreorder (Node *RT) {if(rt==NULL)return; //cout<< "*" <<endl;printf"%d",rt->num); if(++cnt==N) printf ("\ n"); Elseprintf (" "); Preorder (RT-Lson); Preorder (RT-Rson);}voidInorder (Node *RT) { if(rt==NULL)return; //cout<< "*" <<endl;Inorder (rt->Lson); printf ("%d",rt->num); if(++cnt==N) printf ("\ n"); Elseprintf (" "); Inorder (Rt-Rson);}voidPostorder (Node *RT) { if(rt==NULL)return; //cout<< "*" <<endl;Postorder (rt->Lson); Postorder (Rt-Rson); printf ("%d",rt->num); if(++cnt==N) printf ("\ n"); Elseprintf (" ");}Node*insert (Node *rt,intnum) { if(rt==NULL) {rt=Create (NUM); returnRT; } if(num<rt->num) RT->lson=insert (rt->lson,num); Else if(num>rt->num) RT->rson=insert (rt->rson,num);}intMain () { while(SCANF ("%d", &n)! =EOF) {CNTN=0; Node*rt=NULL; for(intI=0; i<n; i++) { intnum; scanf ("%d",&num); RT=Insert (rt,num); }Cnt=0; Preorder (RT); CNT=0; Inorder (RT); CNT=0; Postorder (RT); } return 0;}
Binary sorting tree (achievement, preface, middle order, post-order traversal)