Trees and heaps
引入
7:45
数据结构与算法
这门课讲的是如何根据开销选择容器。第一个单元介绍衡量标准:开销如何随输入规模增长。接下来的四个单元介绍容器:列表、栈和队列、哈希表、树和堆,以及图。最后两个单元介绍算法:排序和搜索。这里所有关于开销的结论,都是在讲义中列出的数据集上统计得出的。
英文讲解 · 可切换中英文字幕
本课内容
| English | 释义 | 拼音 |
|---|---|---|
| binary search tree/ˈbaɪnəri sɜːtʃ triː/ | 二叉搜索树 | èr chā sōu suǒ shù |
| heap/hiːp/ | 堆 | duī |
| min-heap/mɪn hiːp/ | 小顶堆 | xiǎo dǐng duī |
| Extract-min/ˈekstrækt mɪn/ | 取出最小值 | qǔ chū zuì xiǎo zhí |
| Heapsort/ˈhiːpsɔːt/ | 堆排序 | duī pái xù |
| rotation/rəʊˈteɪʃn/ | 旋转 | xuán zhuǎn |
| AVL tree/ˌeɪ viː ˈel triː/ | AVL树 | AVL shù |
有序不变性与完全形状
- 二叉搜索树维持左子树小于节点、右子树大于节点的规则:插入 $50, 30, 70, 20, 40, 60, 80$ 可构建一棵高度为 $2$ 的完美树,且中序遍历读出的序列为 $20, 30, 40, 50, 60, 70, 80$ ——由构造方式自然有序。
- 堆是一种以数组存储的完全树:索引 $i$ 的子节点分别位于 $2i+1$ 和 $2i+2$。最小堆确保每个父节点的值不大于其子节点,因此最小值位于索引 $0$。

In a heap stored as an array, the children of index i sit at —
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The complete shape fixes the mapping: left child 2i+1, right child 2i+2.
这张卡片已更正,翻译更新前会显示英文。
Height is the cost
- A perfect tree of height $h$ holds $2^{h+1} - 1$ nodes: $7$ at $h = 2$, $15$ at $h = 3$, $31$ at $h = 4$. A complete binary tree of $n$ nodes has height $\lfloor \log_2 n \rfloor$; balanced trees have height $O(\log n)$, and their leaves need not all be at the same depth.
- A skewed tree loses this. Inserting the sorted keys $1, 2, 3, 4$ makes a chain of height $3 = n - 1$, so search is $O(n)$. This is why AVL and red-black trees rotate to stay logarithmic.
A perfect tree of height 3 holds —
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
2 to the h+1 minus 1: 16 minus 1 is 15.
遍历与下沉
- 在 BST 中搜索 $40$:先比较 $50$(向左走),再比较 $30$(向右走),最后到达 $40$ ——在 $7$ 个节点上仅用 $3$ 次比较即找到目标。插入 $35$ 并将其挂在 $40$ 左侧;中序遍历结果依然有序。
- 通过插入$5, 3, 8, 1$构建最小堆:$3$上移超过$5$;$1$上移超过$5$再超过$3$;数组变为$[1, 3, 8, 5]$——每个父节点均小于或等于其子节点。
heapq.heapify在$O(n)$时间内通过从中间开始下沉操作构建整个数组。
Search costs the height
Insert 50, 30, 70, 20, 40, 60, 80 to get a perfect tree of height 2, then search for 40. The path visits 50, 30, 40, three comparisons for seven nodes.
Inserting 5, 3, 8, 1 into an empty min-heap leaves the array —
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
3 sifts over 5; 1 sifts over 5 then 3 — parents stay at or below children.
这张卡片已更正,翻译更新前会显示英文。
The heap as a priority queue
- Extract-min 取出最小值 takes the root, moves the last element to index $0$ and sifts it down. From $[1, 3, 8, 5]$: remove $1$, move $5$ to the root to get $[5, 3, 8]$, then swap $5$ with its smaller child $3$: $[3, 5, 8]$. Insert and extract-min each cost $O(\log n)$.
- Heapsort 堆排序 builds a heap in $O(n)$ and then extracts $n$ times: $O(n \log n)$ in place, but not stable. A complete BST of $1000$ keys has height $\lfloor \log_2 1000 \rfloor = 9$, so a search takes at most $10$ node comparisons.
Extract-min on the min-heap $[2, 4, 3, 9, 6]$ leaves the array —
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Move 6 to the root: [6, 4, 3, 9]; its smaller child is 3 at index 2, so swap: [3, 4, 6, 9].
What is the height of a perfectly balanced BST holding 4000 keys?
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
floor(log2 4000) = 11, since 2^11 = 2048 and 2^12 = 4096.
Put the steps of extract-min on an array min-heap in order.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Moving the last element keeps the tree complete; sifting it down then restores the order invariant in at most the height, $O(\log n)$ swaps.
这是一张新卡片,翻译完成前会显示英文。
One rotation keeps it logarithmic
- An AVL tree AVL树 stores each node's balance factor (the height of its left subtree minus the height of its right subtree) and keeps it within $\pm 1$. Insert 1, 2, 3 in that order: node 1 reaches $-2$.
- A left rotation 旋转 makes 2 the root, with children 1 and 3: height 1 instead of 2. Each insert needs at most one single or double rotation, so search stays $O(\log n)$ whatever order the keys arrive in.
Inserting 1, 2, 3 into an empty AVL tree ends with root:
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Node 1 reaches balance -2; a left rotation lifts 2 to the root.
这是一张新卡片,翻译完成前会显示英文。
Worked example: why heapify is O(n)
- Bottom-up heapify sifts down from the middle of the array. A node can sink only as far as its height, and most nodes are near the bottom.
- For $n = 15$: 4 nodes of height 1, 2 of height 2 and 1 of height 3 sink at most $4 + 4 + 3 = \mathbf{11}$ levels in total, fewer than $n$. In general the sum stays below $n$, so building a heap takes linear time, not $n \log n$.
Bottom-up heapify on 15 nodes: the most sift-down swaps in total?
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
$4 \times 1 + 2 \times 2 + 1 \times 3 = 11$.
Building a heap from an unsorted array needs $\Theta(n \log n)$ time.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Inserting one at a time does; bottom-up heapify is $O(n)$.
这是一张新卡片,翻译完成前会显示英文。
Marks that slip away
- Assuming a BST is balanced. Sorted inserts build a chain of height $n - 1$, so search becomes $O(n)$.
- Confusing heap order with BST order. A heap only promises parent $\le$ children: $[1, 3, 8, 5]$ is a valid heap but not sorted.
- Wrong child indices. In a 0-based array the children of $i$ are $2i + 1$ and $2i + 2$, not $2i$ and $2i + 1$.
这张卡片已更正,翻译更新前会显示英文。
Recap
- BST: left $<$ node $<$ right; the inorder walk is sorted; the cost is the height.
- A balanced tree has $O(\log n)$ height; sorted inserts can make an $O(n)$ chain.
- Min-heap in an array: children of $i$ at $2i+1$ and $2i+2$; insert and extract-min are $O(\log n)$.
| Balanced BST | Min-heap | |
|---|---|---|
| Order rule | left $<$ node $<$ right | parent $\le$ children |
| Find any key | $O(\log n)$ | $O(n)$ |
| Find the minimum | $O(\log n)$ | $O(1)$, at the root |
| Stored as | linked nodes | an array |
出了什么问题?只有网站团队能看到这些信息。