typedef struct Node {
int key;
struct Node *left, *right;
} BSTNode, *BSTree;
int bst_insert(BSTree *root, int key) {
BSTree new_node = malloc(sizeof(BSTNode));
new_node->key = key;
new_node->left = new_node->right = NULL;
if (*root == NULL) {
*root = new_node;
return 1;
}
BSTree curr = *root, parent = NULL;
while (curr) {
if (key == curr->key) { free(new_node); return 0; } // 重複
parent = curr;
curr = (key < curr->key) ? curr->left : curr->right;
}
if (key < parent->key) parent->left = new_node;
else parent->right = new_node;
return 1;
}
void bst_create(BSTree *root) {
*root = NULL;
int key;
printf("輸入鍵值 (-1 結束): ");
while (scanf("%d", &key) == 1 && key != -1) {
bst_insert(root, key);
}
}
void bst_inorder(BSTree root) {
if (root) {
bst_inorder(root->left);
printf("%d ", root->key);
bst_inorder(root->right);
}
}
BSTree bst_search(BSTree root, int key) {
while (root) {
if (key == root->key) return root;
root = (key < root->key) ? root->left : root->right;
}
return NULL;
}
int main() {
BSTree root = NULL;
int choice, key;
printf("=== 建立二叉搜索樹 ===\n");
bst_create(&root);
printf("\n中序遍歷 (有序): ");
bst_inorder(root);
printf("\n");
while (1) {
printf("\n輸入查找鍵值 (0 退出): ");
scanf("%d", &key);
if (key == 0) break;
BSTree found = bst_search(root, key);
if (found) printf("找到: %d\n", found->key);
else printf("不存在\n");
}
// 銷毀樹(後序釋放)
void destroy(BSTree r) {
if (r) { destroy(r->left); destroy(r->right); free(r); }
}
destroy(root);
return 0;
}
50
/ \
30 70
/ \ / \
20 40 60 80
二叉搜索樹是動態有序集合的基石數據結構。本文提供了迭代插入、中序遍歷、迭代查找、交互式建樹、記憶體銷毀完整工程級代碼模板。掌握 BST 核心不變量(左 < 根 < 右)與中序遍歷有序性,是理解所有進階搜索樹(AVL、紅黑、B樹、Treap、Splay)的前提。