← C 語言
第 75 課,共 77 課 · 10 XP
樹
理論與題目說明
機器翻譯,尚未經母語人士審閱。
二元搜尋樹(BST)由節點組成,每個節點最多有兩個子節點。左邊的全部比節點小,右邊的全部大於或等於節點:
8
/ \
3 10
/ \ \
1 6 14
struct tree {
int key;
struct tree *left, *right;
};
struct tree *insert(struct tree *t, int key)
{
if (t == NULL) {
struct tree *n = calloc(1, sizeof *n);
n->key = key;
return n;
}
if (key < t->key)
t->left = insert(t->left, key);
else
t->right = insert(t->right, key);
return t;
}
在平衡的樹裡搜尋是 O(log n)——和二分搜尋一樣,但插入也很快。可是如果放進已經排好的資料,樹就會退化成串列。所以實務上會用能自己保持平衡的樹(紅黑樹、AVL 樹)。
中序走訪:左子樹 → 節點 → 右子樹。鍵會依排序的順序出現:
void inorder(const struct tree *t)
{
if (t == NULL)
return;
inorder(t->left);
printf("%d ", t->key);
inorder(t->right);
}
題目。 把輸入的數字放進 BST。第一行用中序走訪顯示鍵,第二行顯示樹的高度(空樹的高度是 0,一個節點是 1)。用遞迴釋放記憶體。