Skip to the content.

leetcode 199 二叉树的右视图


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        result = []
        if not root:
            return result

        current_floor = 0
        q = Queue()
        q.put((root, 1))
        while q.qsize() > 0:
            head, floor = q.get()
            if floor > current_floor:
                result.append(head.val)
                current_floor += 1
            if head.right:
                q.put((head.right, floor + 1))
            if head.left:
                q.put((head.left, floor + 1))
        return result