leetcode 199. 二叉树的右视图

题目链接:leetcode

思路:使用广度优先算法找到一层上的所有节点,第一个就是最右边的

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
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:return []
q = deque()
q.append(root)
res = []
while q:
n = len(q)
for i in range(n):
node = q.popleft()
if i == 0:res.append(node.val)
if node.right:q.append(node.right)
if node.left:q.append(node.left)
return res