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

LeetCode 515: Find Largest Value in Each Tree Row

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

基本資料
#

難易度: medium 第一次嘗試:2026-10-24

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

解題思路
#

BFS 層序遍歷(Tree 模板二),每一層記一個最大值。值的範圍包含負數(到 -2^31),所以每層的初始值要用 -inf。

我的嘗試
#

一次通過。

正確解法
#

class Solution:
    def largestValues(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        res = []
        queue = deque([root])
        while queue:
            best = -inf
            for _ in range(len(queue)):
                node = queue.popleft()
                best = max(best, node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(best)
        return res

複雜度
#

時間 O(n),空間 O(w)。

要特別避免的錯誤
#

  • 每層的最大值初始成 0 會錯,整層都是負數時答案是負的。
  • 空樹回傳 []。

面試口說整理
#

BFS 一層一層走,每層從 -inf 開始取最大值,因為值可以是負的。時間 O(n),空間是最寬那層。也可以用 DFS 帶著深度,res[depth] = max(res[depth], val)。

相關文章

LeetCode 314: Binary Tree Vertical Order Traversal
·1 分鐘
LeetCode Medium Hash-Table Tree Depth-First-Search Breadth-First-Search Sorting Binary-Tree
LeetCode 314 解題筆記:BFS 帶著欄位編號,用 BFS 才能保證同一欄由上到下、同一列由左到右
LeetCode 117: Populating Next Right Pointers in Each Node II
·1 分鐘
LeetCode Medium Linked-List Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 117 解題筆記:BFS 一層一層接 next;不是完全二元樹時,只看隔壁節點的小孩會斷掉
LeetCode 1448: Count Good Nodes in Binary Tree
·1 分鐘
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1448 解題筆記:DFS 往下傳路徑上的最大值,節點的值大於等於它就是好節點
LeetCode 199: Binary Tree Right Side View
·1 分鐘
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 199 解題筆記:層序遍歷,每一層最右邊的節點就是從右邊看得到的
LeetCode 1372: Longest ZigZag Path in a Binary Tree
·1 分鐘
LeetCode Medium Dynamic-Programming Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 1372 解題筆記:每個節點回傳兩個值:從這裡先往左、先往右的最長 zigzag;往左走接的是左小孩「先往右」的值
LeetCode 687: Longest Univalue Path
·1 分鐘
LeetCode Medium Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 687 解題筆記:DFS 回傳往下同值的最長鏈(邊數),在每個節點用左 + 右更新答案