Kodewick
開始學 →
由遍歷序列重建二元樹24 / 52

由遍歷序列重建二元樹

第 24 課,共 52 課 · 第 5 部分 · 樹和堆 · 約 18 分鐘

重建二元樹要前序加中序:前序的第一個是根,它在中序裡的位置把左右子樹分開;用 dict 記下位置就是 O(n),而只有前序加後序是不夠的。

把一棵樹發給別人、存進檔案,只能寫成一串值。上一課的四種遍歷各給出一串,可只拿一串是畫不回來的:[1, 2] 的前序,可能是 1 的左孩子是 2,也可能是右孩子是 2。兩串一起就夠了:前序(或後序)告訴你誰是根,中序告訴你根的左邊有誰、右邊有誰。這是期末和麵試的常考題(LeetCode 105),也是一道很好的「切片看著便宜、其實很貴」的例子:最直白的寫法在 100 層深的樹上要做 1.5 萬次事,改一下只要 300 次左右。

前序找根,中序分左右

還是第 1 課那棵樹:前序 [1, 2, 4, 5, 3, 6],中序 [4, 2, 5, 1, 3, 6]。

  1. 前序的第一個是根:1。
  2. 在中序裡找到 1:它左邊的 4 2 5 是左子樹,右邊的 3 6 是右子樹。左子樹有 3 個結點。
  3. 前序裡,根後面緊跟著的就是整棵左子樹,再後面是右子樹。所以前序裡 1 後面的 3 個 2 4 5 是左子樹的前序,剩下的 3 6 是右子樹的前序。
  4. 左右兩邊各自又是「一串前序加一串中序」:同樣的辦法再做一遍。
前序 + 中序前序中序12453642513601234567891011

前後兩半分別是前序和中序。每一輪:前序第一個是根,中序裡根的左右兩邊就是兩棵子樹,兩串裡的個數正好對得上

同一個過程畫在樹上:每一輪從前序裡拿到一個根,中序決定它掛在哪邊
單選

前序 A B D E C F,中序 D B E A F C。照這一關的辦法建回這棵樹,它的後序是什麼?

單選

前序 [5, 3, 1, 4, 8, 9],中序 [1, 3, 4, 5, 8, 9]。根 5 的左子樹,前序是哪幾個?

最直白的寫法:切片

把上面四步直接翻成 Python,用切片把兩個 list 切成左右兩半:

main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def build(pre, ino):8    if not pre:9        return None10    root = TreeNode(pre[0])11    k = ino.index(pre[0])                  # 左子樹有 k 個結點12    root.left = build(pre[1:k + 1], ino[:k])13    root.right = build(pre[k + 1:], ino[k + 1:])14    return root15 16def postorder(node, out):17    if node:18        postorder(node.left, out)19        postorder(node.right, out)20        out.append(node.val)21    return out22 23root = build([1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6])24print(root.val, root.left.val, root.right.val, root.right.left)25print(postorder(root, []))
輸出
1 2 3 None
[4, 5, 2, 6, 3, 1]

結果對了,後序 [4, 5, 2, 6, 3, 1] 和上一課一樣。可每一層呼叫都要付兩筆賬:ino.index 從頭掃到根的位置;四個切片各複製出一個新 list,加起來約 2n 個元素。樹平衡時每層的 n 加起來是 n log n;樹是一條線時,每一層只比上一層少 1 個,加起來就是 n²。數一數:

main.py
1work = 02 3def build(pre, ino):4    global work5    if not pre:6        return None7    k = ino.index(pre[0])8    work += (k + 1) + 2 * (len(pre) - 1)   # index 掃了 k + 1 個;切片複製了約 2(n − 1) 個9    left = build(pre[1:k + 1], ino[:k])10    right = build(pre[k + 1:], ino[k + 1:])11    return (pre[0], left, right)12 13def balanced_pre(lo, hi, out):             # 1..127 建成平衡的樹時的前序14    if lo <= hi:15        mid = (lo + hi) // 216        out.append(mid)17        balanced_pre(lo, mid - 1, out)18        balanced_pre(mid + 1, hi, out)19    return out20 21work = 022build(balanced_pre(1, 127, []), list(range(1, 128)))23print("平衡的 127 個結點:", work)24 25work = 026build(list(range(1, 101)), list(range(100, 0, -1)))   # 每個結點只有左孩子27print("一條線的 100 個結點:", work)
輸出
平衡的 127 個結點: 1732
一條線的 100 個結點: 14950

一條線的樹只有 100 個結點,卻做了 1.5 萬次事:根每次都在中序的最後,index 要掃完整串,切片又幾乎複製了整串。

單選

切片寫法裡,k = ino.index(pre[0]) 算出的 k 是什麼意思?

單選

切片寫法在一條線(每個結點只有左孩子)的 n 個結點的樹上,總共做多少事?

只傳下標:O(n)

兩筆賬都能省掉:

  • ino.index 每次掃一遍 → 先建一個 dict pos,值 → 在中序裡的下標,之後找根 O(1);
  • 切片複製 → 不切了,只傳中序的邊界 lo, hi。前序也不用切:根總是按前序的順序一個個拿出來,用一個計數器 nxt 記著下一個該拿誰就行。
main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def build_fast(pre, ino):8    pos = {v: i for i, v in enumerate(ino)}   # 值 -> 中序裡的下標9    nxt = 0                                   # 前序裡下一個該當根的10    calls = 011 12    def go(lo, hi):                           # 用 ino[lo..hi] 建一棵子樹13        nonlocal nxt, calls14        calls += 115        if lo > hi:16            return None17        root = TreeNode(pre[nxt])18        nxt += 119        k = pos[root.val]20        root.left = go(lo, k - 1)             # 先左:前序裡左子樹在前面21        root.right = go(k + 1, hi)22        return root23 24    root = go(0, len(ino) - 1)25    return root, calls26 27def postorder(node, out):28    if node:29        postorder(node.left, out)30        postorder(node.right, out)31        out.append(node.val)32    return out33 34root, calls = build_fast([1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6])35print(postorder(root, []), calls)36 37root, calls = build_fast(list(range(1, 101)), list(range(100, 0, -1)))38print("一條線的 100 個結點:", calls, "次呼叫")
輸出
[4, 5, 2, 6, 3, 1] 13
一條線的 100 個結點: 201 次呼叫

每個結點進一次 go,每個空位也進一次:2n + 1 次呼叫,每次 O(1),加上建 dict 的 n 次,一共 O(n)。順序也要注意:必須先建左子樹、再建右子樹,因為前序裡左子樹的結點全排在右子樹前面,nxt 是按這個順序往後走的。

兩種寫法都假設值互不相同;有重複的值,中序裡就找不準根在哪了。

寫法找根分兩半平衡的樹一條線的樹
切片 + index掃一遍,O(n)複製,O(n)O(n log n)O(n²)
dict + 邊界查 dict,O(1)只傳 lo、hi,O(1)O(n)O(n)
猜輸出猜錯也沒關係

前序 [3, 9, 20, 15, 7],中序 [9, 3, 15, 20, 7]。建好以後印出後序,是什麼?

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def build(pre, ino):8    if not pre:9        return None10    root = TreeNode(pre[0])11    k = ino.index(pre[0])12    root.left = build(pre[1:k + 1], ino[:k])13    root.right = build(pre[k + 1:], ino[k + 1:])14    return root15 16def post(node, out):17    if node:18        post(node.left, out)19        post(node.right, out)20        out.append(node.val)21    return out22 23print(post(build([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]), []))
單選

dict 加邊界的寫法裡,為什麼必須先建左子樹、再建右子樹?

練習 1

中序加後序

補全 build(ino, post):用中序和後序重建二元樹。後序的最後一個是根;從後往前拿根時,先拿到的是右子樹的根,所以要先建右子樹。

要顯示
[3, 9, 20, 15, 7]
[1, 2, 4, 5, 3, 6]
[]
exercise1.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def build(ino, post):8    pos = {v: i for i, v in enumerate(ino)}9    nxt = len(post) - 1                   # 後序裡下一個該當根的(從後往前)10 11    def go(lo, hi):12        nonlocal nxt13        # lo > hi 返回 None;否則拿 post[nxt] 當根,nxt 減一,再建兩邊14        return None15 16    return go(0, len(ino) - 1)17 18def pre(node):19    return [node.val] + pre(node.left) + pre(node.right) if node else []20 21print(pre(build([9, 3, 15, 20, 7], [9, 15, 7, 20, 3])))22print(pre(build([4, 2, 5, 1, 3, 6], [4, 5, 2, 6, 3, 1])))23print(pre(build([], [])))
輸出
點「執行」或按 Ctrl+Enter
練習 2

不建樹,直接出後序

補全 to_post(pre, ino):給前序和中序,返回後序,不造任何結點。還是「前序找根、中序分左右」,只是不建結點,而是在兩邊都處理完以後把根 append 到 out 裡。

要顯示
[4, 5, 2, 6, 3, 1]
[9, 15, 7, 20, 3]
[3, 2, 1]
exercise2.py
1def to_post(pre, ino):2    pos = {v: i for i, v in enumerate(ino)}3    nxt = 04    out = []5 6    def go(lo, hi):7        nonlocal nxt8        # lo > hi 直接返回;否則拿 pre[nxt] 當根,先處理左邊、再處理右邊,最後把根放進 out9        return10 11    go(0, len(ino) - 1)12    return out13 14print(to_post([1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6]))15print(to_post([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]))16print(to_post([1, 2, 3], [3, 2, 1]))
輸出
點「執行」或按 Ctrl+Enter

前序加後序為什麼不夠

前序和後序都只告訴你誰是根,沒有一串能告訴你剩下的結點在根的哪一邊。最小的反例只有兩個結點:

main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def pre(node):8    return [node.val] + pre(node.left) + pre(node.right) if node else []9 10def ino(node):11    return ino(node.left) + [node.val] + ino(node.right) if node else []12 13def post(node):14    return post(node.left) + post(node.right) + [node.val] if node else []15 16a = TreeNode(1, TreeNode(2), None)       # 2 是左孩子17b = TreeNode(1, None, TreeNode(2))       # 2 是右孩子18print("前序", pre(a), pre(b))19print("後序", post(a), post(b))20print("中序", ino(a), ino(b))
輸出
前序 [1, 2] [1, 2]
後序 [2, 1] [2, 1]
中序 [2, 1] [1, 2]

兩棵不同的樹,前序一樣、後序也一樣,只有中序分得開:只有一個孩子時,前序和後序都分不出它在左還是右。所以重建總要中序加上另一種:

給的兩串能唯一確定嗎根從哪來
前序 + 中序能前序的第一個
後序 + 中序能後序的最後一個
層序 + 中序能層序的第一個
前序 + 後序不一定只有每個結點都是 0 個或 2 個孩子時才能

面試裡: 寫完要說複雜度:dict 加邊界是 O(n) 時間、O(n) 空間(dict 加遞迴堆疊)。追問「為什麼先建左子樹」「有重複值怎麼辦」「前序加後序行不行」,答案都在這一課。

單選

下面哪兩串遍歷不一定能唯一確定一棵二元樹?

單選

中序 [2, 1, 3],後序 [2, 3, 1]。這棵樹的前序是什麼?

工作裡這樣寫

真要把一棵樹存下來再讀回去(LeetCode 297「序列化」),工作裡不會存兩串遍歷,而是存一串帶空位標記的前序:遇到 None 也寫一個 #。空位標記補上了「在哪一邊」的資訊,所以一串就夠了。讀回來時用 iter 和 next 按順序一個個取:

main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def dumps(node):8    if node is None:9        return ["#"]10    return [str(node.val)] + dumps(node.left) + dumps(node.right)11 12def loads(tokens):13    it = iter(tokens)14    def go():15        t = next(it)16        if t == "#":17            return None18        return TreeNode(int(t), go(), go())   # 引數從左往右算:先左後右19    return go()20 21root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),22                TreeNode(3, None, TreeNode(6)))23s = ",".join(dumps(root))24print(s)25back = loads(s.split(","))26print(",".join(dumps(back)) == s, back.right.right.val)
輸出
1,2,4,#,#,5,#,#,3,#,6,#,#
True 6
  • 資料本來就是巢狀的 dict 和 list 時,直接 json.dumps;自己的 TreeNode 才需要上面這樣轉一下。
  • 上面的 dumps 每層都在拼 list,一條線的樹會是 O(n²);量大時改成往同一個 list 裡 append。
  • 題目給兩串遍歷讓你重建時,預設寫 dict 加邊界的版本。
猜輸出猜錯也沒關係

帶空位標記的前序:1 只有右孩子 2。印出什麼?

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def dumps(node):8    if node is None:9        return ["#"]10    return [str(node.val)] + dumps(node.left) + dumps(node.right)11 12print(",".join(dumps(TreeNode(1, None, TreeNode(2)))))

小結

這一課帶走

前序找根,中序分左右

  • 前序第一個(後序最後一個)是根;中序裡根的左邊是左子樹,右邊是右子樹
  • 切片版簡單,但每層 index 加複製 O(n):一條線的樹 O(n²)
  • dict 記中序下標 + 只傳 lo、hi + 計數器拿根:O(n);前序先建左,後序先建右
  • 前序加後序分不清只有一個孩子時在哪邊;要有中序
  • 存一棵樹:一串帶 # 空位標記的前序就夠了
1pos = {v: i for i, v in enumerate(ino)}2def go(lo, hi):              # nxt:前序裡下一個根3    if lo > hi: return None4    root = TreeNode(pre[nxt]); nxt += 15    k = pos[root.val]6    root.left, root.right = go(lo, k - 1), go(k + 1, hi)