↓快轉到主要內容
  1. LeetCode/

LeetCode 2509: Cycle Length Queries in a Tree

·1 分鐘· ·
LeetCode Hard Tree Binary-Tree Lca
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: hard 第一次嘗試:2026-09-11

  • 提交紀錄:Accepted(一次通過)

解題思路
#

在 a、b 之間加一條邊,形成的環就是「樹上 a 到 b 的路徑」再加上新的那條邊。所以:

環長 = dist(a, b) + 1

這棵樹的編號跟 heap 一樣:根是 1,v 的子節點是 2v 和 2v + 1,parent 是 v // 2。

要算 dist(a, b),就讓兩個節點往上爬到最低共同祖先(LCA)。值比較大的節點一定在同一層或更深,所以每次把比較大的那個除以 2,直到兩者相等,爬了幾步就是距離。

我的解法
#

class Solution:
    def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:
        res = []
        for x, y in queries:
            step = 1                  # 新加的那條邊
            while x != y:
                if x > y:
                    x //= 2
                else:
                    y //= 2
                step += 1
            res.append(step)
        return res

複雜度
#

每個查詢最多爬 2n 步(樹高是 n),時間 O(m * n),n <= 30。空間 O(1),不算輸出。

要特別避免的錯誤
#

  • 真的把樹建出來再跑 BFS:樹有 2^30 個節點,建不出來。
  • 忘記加上新增的那條邊,答案少 1。
  • 只讓其中一個節點往上爬:要每次移動比較深的那個。

面試口說整理
#

加一條邊形成的環,長度是樹上兩點距離加 1。這棵樹的編號跟 heap 一樣,parent 是 v // 2,而且值比較大的節點一定不會比較淺,所以每次把比較大的除以 2,直到兩點相同,爬的步數就是距離。每次查詢最多 O(n) 步,n 最多 30。

相關文章

LeetCode 865: Smallest Subtree with all the Deepest Nodes
·1 分鐘
LeetCode Medium Tree Binary-Tree Bfs Dfs Lca
LeetCode 865 解題筆記:BFS 找最後一層再一起往上爬,或一次 DFS 回傳 (深度, 節點)
LeetCode 2421: Number of Good Paths
·2 分鐘
LeetCode Hard Tree Union-Find Graph Sorting
LeetCode 2421 解題筆記:依值由小到大加入節點,用 Union-Find 數同一群裡同值的節點
LeetCode 1373: Maximum Sum BST in Binary Tree
·1 分鐘
LeetCode Hard Dynamic-Programming Tree-Dp Binary-Search-Tree Depth-First-Search Tree
LeetCode 1373 解題筆記:後序遍歷回傳 (總和, 最小值, 最大值, 是不是 BST);左子樹的最大值 < 自己 < 右子樹的最小值才是 BST
LeetCode 1377: Frog Position After T Seconds
·2 分鐘
LeetCode Hard Tree Dfs Bfs Graph Probability
LeetCode 1377 解題筆記:無向邊、seen 要記節點、提早到達目標時要看還能不能走
LeetCode 2196: Create Binary Tree From Descriptions
·1 分鐘
LeetCode Medium Tree Binary-Tree Hash-Map
LeetCode 2196 解題筆記:用 dict 存節點一次連好,根是唯一不是任何人子節點的值
LeetCode 2603: Collect Coins in a Tree
·2 分鐘
LeetCode Hard Tree Graph Topological-Sort
LeetCode 2603 解題筆記:先剪掉沒有硬幣的葉子,再固定剪兩層,剩下的邊走兩次