LeetCode 筆記 - 515. Find Largest Value in Each Tree Row

題目在此 515. Find Largest Value in Each Tree Row

給定一棵 Binary Tree,請回傳每一層最大的數字

解題思維

可以使用 Breadth-First Search 一次走訪同一層的節點

紀錄看到最大數值即可

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:

if not root:
return root

upper_quque = [root]
lower_quque = []

result = []
while upper_quque:

current_max = -inf
for node in upper_quque:
if node.left:
lower_quque.append(node.left)
if node.right:
lower_quque.append(node.right)
current_max = max(current_max, node.val)

if current_max != -inf:
result.append(current_max)

upper_quque = lower_quque
lower_quque = []

return result

也許你也會想看看