1 题目
2 思想
层序遍历,输出值的时候只需要获取每层的第一个节点就可以了
3 代码
# 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
from queue import Queue
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
que = Queue()
tmp = []
res = []
if root is None:
return res
tmp.append(root)
while(len(tmp)):
res.append(tmp[0].val)
# 将tmp中的值入队列
for node in tmp:
que.put(node) # 将节点放到队列中
tmp.clear()
while(not que.empty()): #当队列非空
cur_root = que.get()
if cur_root.right is not None:
tmp.append(cur_root.right)
if cur_root.left is not None:
tmp.append(cur_root.left)
return res