LeetCode 筆記 - 199. Binary Tree Right Side View

要求回傳二元樹從右側觀察到的視圖節點。本文運用廣度優先搜尋(BFS)進行層序遍歷,並精確搜集每一層最後出現的節點。這是一個理解如何透過層級探索來提取樹狀結構視覺屬性的經典實作案例。

發佈
閱讀
約 1 分鐘
字數
200
⚠️ 舊文提醒:本文發佈於約 4 年前,部分內容或指令可能已過時,請斟酌參考。

題目在此 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

也許你也會想看看

輸入關鍵字開始搜尋 · ↑↓ 選擇 · Enter 開啟