Skip to main content

Binary Tree Right Side View

Question

What is the order of the nodes from right to left when viewed from the right side of a binary tree?

Example 1
Input: 
1
/ \
2 3
/ \ \
4 5 6

Output: [1, 3, 6]

Solution

all//Binary Tree Right Side View.py


# 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):
res = []
if not root:
return res

queue = [root]
while queue:
level_size = len(queue)
for i in range(level_size):
cur_node = queue.pop(0)

if i == level_size - 1:
res.append(cur_node.val)

if cur_node.left:
queue.append(cur_node.left)
if cur_node.right:
queue.append(cur_node.right)

return res