Binary Tree Right Side View
MediumNeetCode 150Top Interview 150 TreesMetaWixProblem
Imagine standing to the right of a binary tree and looking at it. Given the root, return the values
of the nodes you can see, ordered from top to bottom.
On each level you see only the rightmost node. The tree is given in level order, with null for a
missing child.
Constraints
- 0 ≤ number of nodes ≤ 100
- -100 ≤ Node.val ≤ 100
Examples: pick one to animate
Solutions
Time: Every node is added to the queue once and taken out once, with constant work each time.
Space: The queue holds at most one or two levels at a time, so it is as large as the widest level, w. That can reach n/2.
Walk the tree level by level with a queue. At the start of each round the queue holds exactly one level, so save its size. The nodes come out left to right, so the one at position size - 1 is the rightmost. Record only that one, and still queue the children of every node.