199.二叉树的右视图

难度:中等
题目描述:
199.二叉树的右视图_第1张图片
思路总结:层次遍历,本来想昨天一起写完的,但是觉着一天不能写两次吧,所有留今天写了。
题解一:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        if not root:return []
        res = []
        queue = deque([root, ])
        next_len = 0
        while queue:
            next_len = len(queue)
            while next_len > 0:
                cur = queue.popleft()
                if next_len == 1:
                    res.append(cur.val)
                if cur.left:queue.append(cur.left)
                if cur.right:queue.append(cur.right)
                next_len -= 1
        return res

题解一结果:
199.二叉树的右视图_第2张图片

你可能感兴趣的:(朱滕威的面试之路)