Binary Tree Right Side View
Problem: Binary Tree Right Side View
We can use both breadth-first search or depth-first search to solve the problem. Each methods suits different cases. We use breadth-first search here.
Code in Python:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root: return []
queue, res = [root], []
while queue:
res.append(queue[-1].val)
next = []
for node in queue:
if node.left: next.append(node.left)
if node.right: next.append(node.right)
queue = next
return res