LeetCode 筆記 - 1302. Deepest Leaves Sum

題目在此 1302. Deepest Leaves Sum

給定一個 Binary Tree,計算出最深 node 的總和

image 10

解題思維

這題的關鍵就是找出同一層的 node 有哪些
在這裡 Breadth-First Search 剛好可以幫上我們的忙

透過搜索的順序,最終我們就可以知道 最底層的 node 有哪些

程式碼

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
# 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 deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
if not root:
return root

upper_quque = [root]
lower_quque = []

result = 0
while upper_quque:
for node in upper_quque:
if node.left:
lower_quque.append(node.left)
if node.right:
lower_quque.append(node.right)
if not lower_quque:
for node in upper_quque:
result += node.val
break
upper_quque = lower_quque
lower_quque = []

return result

也許你也會想看看