199. Binary Tree Right Side View

Intuition

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.

Solution

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:
            return
        if depth >= len(self.views):
            self.views.append(None)
        self._helper(node.left, depth + 1)
        self.views[depth] = node.val
        self._helper(node.right, depth + 1)

Information

  • Created: 2018-12-11 08:42:37

  • Last Motified: 2020-01-13 21:15:06

  • Tags: Tree, Depth-first Search, Breadth-first Search