199. Binary Tree Right Side View

Question: Binary Tree Right Side View

Solution

  1. 先找出每一層有誰 → 分層 → BFS → queue
  2. 再找該層最右邊是誰
    1. 該層每一個 node ,從最前面開始取出: queue.popleft()
    2. 取出後,看他的 left & right children,放入 queue 的後面: queue.append(left/right children)
    3. 取到該層的最後一個值,記起來: ans.append(last_node.val)
# 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]:
ans = list()
if root == None:
return ans
q = deque([root])
while q:
for i in range(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans.append(node.val)
return ans

Video Solution



Comments

Popular Posts