This page looks best with JavaScript enabled

Leetcode 199 Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

my solution

Success Details >

Runtime:Β 20 ms, faster than 99.66% of Python3 online submissions for Binary Tree Right Side View.

Memory Usage:Β 14.3 MB, less than 20.55% of Python3 online submissions for Binary Tree Right Side View.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# 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: TreeNode) -> List[int]:
        if not root:
            return []
        re, q = [], [root]
        while q:
            nxt = []
            re += [q[-1].val]
            for n in q:
                for c in [n.left, n.right]:
                    if c:
                        nxt += [c]
            q = nxt
        return re