二叉搜索树利用其特有的二叉树性质,使其搜索更方便
源代码:
struct node { int val; node *left, *right; }; //the function of insert node *insert(node *n, int key) { if (n == NULL) { node *t = new node; t->val = key; t->left = t->right = NULL; return t; } else { if (key < n->val) n->left = insert(n->left, key); else n->right = insert(n->right, key); return n; } } //the function of find_key bool find(node *n, int key) { if (n == NULL) return false; else if (key == n->val) return true; else if (key > n->val) return find(n->right, key); else return find(n->left, key); } //the function of remove node *remove(node *n, int key) { if (n == NULL) return NULL; else if (key < n->val) n->left = remove(n->left, key); else if (key > n->val) n->right = remove(n->right, key); else if (n->left == NULL) { node *q = n->right; delete n; return q; } else if (n->left->right == NULL) { node *q = n->left; q->right = n->right; delete n; return q; } else { node *q; for (q = n->left; q->right->right != NULL; q = q->right); node *r = q->right; q->right = r->left; r->left = n->left; r->right = n->right; delete n; return r; } return n; }
利用STL实现