Binary Tree Right Side View

Problem Id: 199 Difficulty: Medium Tag: Tree Tag: Depth-first Search Tag: Breadth-first Search


We could solve this problem using inorder traversal DFS with an additional variable depth. And mark & overwrite the view of the tree. Finally, left nodes would be in the view.


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        self.views = []
        self._helper(root, 0)
        return self.views

    def _helper(self, node, depth):
        if node is None:
        if depth >= len(self.views):
        self._helper(node.left, depth + 1)
        self.views[depth] = node.val
        self._helper(node.right, depth + 1)