Binary Tree Right Side View
Description
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
const rightSideView = (root) => {
let frontier = [root]
const res = []
while (frontier.length) {
if(frontier[frontier.length - 1]) {
res.push(frontier[frontier.length - 1].val)
}
frontier = frontier.reduce((next, node) => {
if(!node) {
return next
}
if (node.left) {
next.push(node.left)
}
if (node.right) {
next.push(node.right)
}
return next
}, [])
}
return res
}