Binary Tree Right Side View
Imagine standing to the right of a binary tree and looking at it. On each level you can see only one node: the rightmost one on that level, which hides everything to its left.
Given the root of the tree, return the values you can see, ordered from the top level to the bottom one. Return an empty array for an empty tree.
Note that the visible node on a deep level can be in the left half of the tree, if nothing on that level sits further right.
Constraints
- The tree has between
0and100nodes. -100 <= Node.val <= 100
Examples
Example 1
Input: root = [1,2,3,4,5,null,6,null,7] Output: [1,3,6,7]
Rightmost per level: 1, then 3, then 6. On level 4 the only node is 7, under 4 on the far left, and nothing on that level is further right.
Example 2
Input: root = [1,2] Output: [1,2]
Level 2 holds only the left child 2, so it is visible from the right.
Example 3
Input: root = [] Output: []
An empty tree shows nothing.
JavaScript you'll use: Stacks, queues and deques Arrays: create, read, update
/**
* Tree nodes are provided (you don't need to define them):
* class TreeNode { constructor(val = 0, left = null, right = null) { this.val = val; this.left = left; this.right = right; } }
*/
/**
* @param {TreeNode | null} root
* @return {number[]}
*/
function rightSideView(root) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.