注意要插入的值,如果等于当前节点,就把它变成当前节点的右儿子
此代码是中南大学暑训入门 B题的AC代码
#include#define ll long longusing namespace std;struct node{ ll data; node * lson; node * rson;}*head;int t;void build(ll x,node *p){ if(p==NULL){ node * pp; pp=new node ; pp->data=x; pp->lson=NULL; pp->rson=NULL; head=pp; return; } if(p->data<=x&&p->rson){build(x,p->rson);} else if(p->data>x&&p->lson){build(x,p->lson);} else if(p->data<=x&&!p->rson){ node * pp; pp=new node ; pp->data=x; pp->lson=NULL; pp->rson=NULL; p->rson=pp; } else if(p->data>x&&!p->lson){ node * pp; pp=new node ; pp->data=x; pp->lson=NULL; pp->rson=NULL; p->lson=pp; }}void preview(node *p){ if(p==NULL){return;} if(t){cout<<" ";} cout< data;t++; preview(p->lson); preview(p->rson);}void midview(node *p){ if(p==NULL){return;} midview(p->lson); if(t)cout<<" "; cout< data;t++; midview(p->rson);}void posview(node *p){ if(p==NULL){return;} posview(p->lson); posview(p->rson); if(t){cout<<" ";} cout< data;t++;}void delet(node *p){ if(p==NULL){return;} delet(p->lson); delet(p->rson); delete p;}int main(){ int T; while(cin>>T) while(T--){ int n; ll x; cin>>n; head=NULL; for(int i=0;i >x; build(x,head); } t=0; preview(head); cout<