完整代码:插入,查找,删除
struct BST { int val; BST *lch, *rch; BST *insert(BST *p, int x) { if (p == NULL) { BST *t = new BST; //new出来的不是指向NULL的 t->val = x; t->lch = t->rch = NULL; return t; } if (x <= p->val) p->lch = insert (p->lch, x); else p->rch = insert (p->rch, x); return p; } bool find(BST *p, int x) { if (x == p->val) return true; else if (p == NULL) return false; else if (x <= p->val) { return find (p->lch, x); } else { return find (p->rch, x); } } BST *remove(BST *p, int x) { //返回被删除后的新结点的地址 if (p == NULL) return NULL; else if (x <= p->val) p->lch = remove (p->lch, x); else if (x > p->val) p->rch = remove (p->rch, x); else if (p->lch == NULL) { //如果需要删除的结点没有左儿子,那么把右儿子提上去 BST *t = p->rch; delete p; return t; } else if (p->lch->rch == NULL) { //如果需要删除的结点的左儿子没有右儿子,那么把左儿子提上去 BST *t = p->lch; t->rch = p->rch; delete p; return t; } else { //以上两种情况不满足,把左儿子子孙中值最大的结点提上去 BST *t = p->lch; while (t->rch->rch != NULL) t = t->rch; BST *r = t->rch; t->rch = r->lch; r->lch = p->lch; r->rch = p->rch; delete p; return r; } return p; }}bst;