Skip to the code
cf.
+25 XP

#326 Visible From the Right Edge

medium

A minimap of a nested layout shows, for each depth, only the node closest to the right edge of the screen.

Write rightEdge(root) that returns, for each level from the top down, the value of the rightmost node on that level. An empty tree returns [].

Example 1

Input: root = [1,2,3,4]
Output: [1,3,4]

Level 2 has only 4, even though it hangs on the left side.

Example 2

Input: root = [6,2,8,null,4]
Output: [6,8,4]

4 is the only node on level 2.

Constraints

  • 0 <= number of nodes <= 10000

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).