樹(Tree)

有根樹把節點組織成層級,除根外每個節點只有一個父節點。它適合表示可遞歸分解的層級數據;一般無向樹則是連通且無環的圖。

一句話定義

有根樹把節點組織成層級,除根外每個節點只有一個父節點。它適合表示可遞歸分解的層級數據;一般無向樹則是連通且無環的圖。

為什麼重要

  • 層級數據無處不在:檔案系統、HTML/DOM、JSON、組織架構、程式碼的語法樹(AST)。
  • 許多高效結構都是特化的樹:二叉搜索樹、堆、Trie、B 樹(資料庫索引)、決策樹(機器學習模型)。

使用邊界

深度與高度有按邊數、按層數計數的不同約定。本批示例的 height 返回層數,葉子高度為 1;共享子節點、符號連結或回指會讓實際結構成為圖。

原理 / 圖解

圖 1
術語 含義
根(root) 沒有父節點的節點
葉子(leaf) 沒有子節點的節點
深度 / 高度 深度常按根到節點的邊數;本篇 height 示例按子樹層數計高度,葉子高度為 1
子樹 任一節點及其所有後代

一棵有 nn 個節點的樹恰好有 n−1n-1 條邊。樹天然適合遞歸:一棵樹 = 根 + 若干棵子樹。

可運行示例

用類表示檔案樹,遞歸打印、求高度與葉子數、查找路徑;再看 Python 自帶的語法樹 ast 和 JSON 嵌套結構(Python 3.15.0 一稿運行記錄):

# 檔案:examples/13_tree.py
# 樹:有層級、無環的結構。檔案系統、DOM、JSON、AST、組織架構都是樹
from dataclasses import dataclass, field

@dataclass
class TreeNode:
    name: str
    children: list["TreeNode"] = field(default_factory=list)
    def add(self, *kids): self.children.extend(kids); return self

root = TreeNode("project").add(
    TreeNode("src").add(TreeNode("main.py"), TreeNode("utils.py")),
    TreeNode("tests").add(TreeNode("test_main.py")),
    TreeNode("README.md"))

def show(node, prefix=""):                   # 前序遍歷:先處理自己再處理孩子
    print(prefix + node.name)
    for c in node.children: show(c, prefix + "  ")
show(root)

def height(n): return 1 + max((height(c) for c in n.children), default=0)
def count_leaves(n): return 1 if not n.children else sum(count_leaves(c) for c in n.children)
print("高度:", height(root), "| 葉子數:", count_leaves(root))

def path_to(n, target, path=()):
    path = path + (n.name,)
    if n.name == target: return "/".join(path)
    for c in n.children:
        if (p := path_to(c, target, path)): return p
print("查找路徑:", path_to(root, "test_main.py"))

# Python 程式碼本身就是一棵樹(AST)
import ast
tree = ast.parse("y = (a + b) * 2")
print(ast.dump(tree.body[0].value, indent=1)[:200])

# JSON 也是樹
import json
doc = json.loads('{"model": {"name": "x", "layers": [{"type": "attn"}, {"type": "mlp"}]}}')
print("JSON 樹深處取值:", doc["model"]["layers"][1]["type"])

一稿留存輸出:

project
  src
    main.py
    utils.py
  tests
    test_main.py
  README.md
高度: 3 | 葉子數: 4
查找路徑: project/tests/test_main.py
BinOp(
 left=BinOp(
  left=Name(id='a'),
  op=Add(),
  right=Name(id='b')),
 op=Mult(),
 right=Constant(value=2))
JSON 樹深處取值: mlp

ast.dump 顯示 (a + b) * 2 的語法樹:乘法是根,左子樹是加法——括號決定了樹的形狀,也決定了計算順序。ast 模塊:https://docs.python.org/3/library/ast.html

常見誤區

  • 深度與高度的定義不統一:有的教材從 0 計、有的從 1 計,讀題時先確認。
  • 很深的樹用遞歸遍歷:可能觸發遞歸上限(見 k2.ds.stack),可改用顯式棧。
  • 把有共享子節點的結構當樹處理:一個節點有兩個父節點就是圖(DAG)了(見 k2.ds.graph),遍歷時要防重複。

與 AI 開發的關係

  • 決策樹與隨機森林:sklearn 的樹模型(見 k2.ml.sklearn)、XGBoost/LightGBM 的梯度提升樹。
  • 程式碼智能:程式碼分析、重構工具和部分程式碼模型基於 AST 或 tree-sitter 語法樹。https://tree-sitter.github.io/tree-sitter/
  • 思維樹(Tree of Thoughts):把 LLM 推理組織為樹狀搜索。https://arxiv.org/abs/2305.10601
  • 文檔切分:按標題層級(Markdown 樹)切分文檔用於 RAG。

延伸閱讀

理解檢查

目錄中有指向父目錄的連結,能無條件按樹遞歸嗎?

參考答案:不能。需要識別連結或維護訪問記錄,避免重複遍歷或循環。

核驗與復現

核驗日期:2026-10-14。示例狀態:運行通過。本輪日誌:13_tree.py。

配套程式碼與核驗資料

繼續瀏覽基礎 返回知識 →返回頂部 ↑
本篇目錄
教程圖解100%
教程圖解