Complexity O (LOGN)
1#include <queue>2#include <cstdio>3 using namespacestd;4 5 //represents the structure of a node6 structnode{7 intVal;8Node *lch,*RCH; 9 };Ten One //Insert value x ANode *intsert (node *p,intx) - { - if(p==NULL) { theNode *q=Newnode; -Q->val=x; -Q->lch=q->rch=NULL; - returnQ; + } - Else{ + if(X < p->val) AP->lch=intsert (p->lch,x); at Else -P->rch=intsert (p->rch,x); - returnp; - } - } - in //Find value x - BOOLFind (Node *p,intx) to { + if(P==null)return false; - Else if(x = = P->val)return true; the Else if(x < P->val)returnFind (p->lch,x); * Else returnFind (p->rch,x); $ }Panax Notoginseng - //Delete value x theNode *remove (node *p,intx) { + if(P==null)returnNULL; A Else if(x < P->val) P->lch=remove (p->lch,x); the Else if(x > P->val) p->rch=remove (p->rch,x); + Else if(p->lch==NULL) { -Node *q=p->ch; $ delete p; $ returnQ; - } - Else if(p->lch->rch==NULL) { theNode *q=p->LCH; -Q->rch=p->rch;Wuyi delete p; the returnQ; - } Wu Else{ -Node *Q; About for(q=p->lch;q->rch->rch!=null;q=q->rch); $Node *r=q->rch; -Q->rch=r->LCH; -R->lch=p->LCH; -R->rch=p->rch; A delete p; + returnR; the } - returnp; $}
Implementation of binary search tree