LeetCode 筆記 - 199. Binary Tree Right Side View

題目在此 199. Binary Tree Right Side View

給定一個 Binary Tree,請計算出從右側看到的 node
image 41

解題思維

這題就是使用 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
30
31
32
# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:

if not root:
return []


upper = [root]
lower = []

result = []
while upper:

result.append(upper[-1].val)
while upper:
current_node = upper.pop(0)

if current_node.left:
lower.append(current_node.left)
if current_node.right:
lower.append(current_node.right)

upper = lower
lower = []

return result

也許你也會想看看