Binary Tree Right Side View

Medium#199tree nodes

You get the root of a binary tree, possibly none. Imagine standing to the right of it: list the values you can see, from the top down. On each level only the rightmost node is visible. Our example is the tree [6, 2, 9, 5, 4, none, 11, none, none, 8] in level order — the answer is [6, 9, 11, 8].

input
root: a binary tree, written as on LeetCode: its values level by level, left to right, null for a missing child.
returns
What is seen of it from the right: the rightmost value of each level, from the root down; [] for an empty tree.
constraints
  • 0 ≤ the number of nodes ≤ 100
  • −100 ≤ Node.val ≤ 100
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
function rightSideView(root) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more breadth-first search (bfs) problems

Pattern “Breadth-first search (BFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.