二叉搜尋樹(BST)C 視覺化:一步步看懂
每個結點的左子樹都比它小、右子樹都不比它小。插入和查詢都從根出發,比它小往左、比它大往右,每一層只走一邊。
binary_search_tree.c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int key;
struct Node *left, *right;
} Node;
Node *insert(Node *root, int key) {
if (root == NULL) {
Node *n = malloc(sizeof(Node));
n->key = key;
n->left = n->right = NULL;
return n;
}
if (key < root->key) root->left = insert(root->left, key);
else root->right = insert(root->right, key);
return root;
}
int search(Node *root, int key) {
while (root && root->key != key)
root = key < root->key ? root->left : root->right;
return root != NULL;
}
int main(void) {
int keys[] = {8, 3, 10, 1, 6, 14};
Node *root = NULL;
for (int i = 0; i < 6; i++) root = insert(root, keys[i]);
printf("%d %d\n", search(root, 6), search(root, 7));
return 0;
}
二叉搜尋樹是怎麼做的
- 從根開始,比較要找(或要插入)的 key 和當前結點。
- 比當前結點小就往左,否則往右。
- 插入:走到空位,就在這裡放一個新結點。
- 查詢:遇到一樣的就找到了;走到空位說明不在樹裡。
看的時候盯住這兩個
走的路線每一層只往左或往右走一次,看它走過幾個結點。
新結點掛在哪6 比 8 小往左、比 3 大往右,於是掛在 3 的右邊。
常見問題
二叉搜尋樹查詢的時間複雜度是多少?
和樹的高度成正比:比較平衡時是 O(log n);按排好的順序插入會退化成一條線,變成 O(n)。
怎麼避免退化?
用會自己保持平衡的樹,比如 AVL 樹、紅黑樹。C++ 的 std::map 就是紅黑樹。
中序遍歷二叉搜尋樹會得到什麼?
從小到大排好序的序列。