Imagine standing on the right side of a binary tree. Return the values of the nodes you can see, from top to bottom.
Traverse level by level. The last node of each level is the one you see from the right.
1function rightSideView(root: TreeNode | null): number[] {2const res: number[] = [];3let level = root ? [root] : [];4while (level.length) {5res.push(level.at(-1)!.val);6level = level.flatMap((n) => [n.left, n.right].filter((c): c is TreeNode => !!c));7}8return res;9}
First level is the root.
Space: play/pause · ←/→: step