Skip to contentKEEP THE CRAFTTHE SANCTUARY

Binary Tree Right Side View

Return the value you would see at each level when looking at the tree from the right.

The problem

Implement Solution.rightSideView(root). root is the root TreeNode of a binary tree, or None for an empty tree; each node has val, left and right. Imagine standing to the right of the tree: at each level you see only the rightmost node. Return those values from the top level to the bottom one. Return [] for an empty tree. Trees are written in level order with None for a missing child. For [1, 2, 3, None, 5, None, 4] return [1, 3, 4]. For [1, 2, 3, 4] return [1, 3, 4]: the third level has only the node 4, which hangs on the left side, so it is still the one you see. Constraints: the tree has 0 to 100 nodes; values are integers from -100 to 100. Do not change the tree.

Starter code

class Solution:
    def rightSideView(self, root):
        pass

Public examples

  1. root = [1, 2, 3, None, 5, None, 4]gives[1, 3, 4]
  2. root = [1, 2, 3]gives[1, 3]
  3. root = [-9]gives[-9]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.