Loading content...
You are given the root of a binary tree. Your task is to traverse the tree and identify the rightmost node at each level when the tree is observed from its right edge. Return a list containing the values of these rightmost nodes, ordered sequentially from the top level (root) to the bottom level.
Visualize the tree as if you were standing on its right side and looking at it from that perspective. At each horizontal level, you can only see the node that appears furthest to the right. The first visible node is the root (topmost level), and the last visible node is the rightmost node at the deepest level.
If the tree is empty (i.e., root is null), return an empty list.
root = [1,2,3,null,5,null,4][1,3,4]The tree structure is:
1 <-- Level 0: rightmost is 1
/
2 3 <-- Level 1: rightmost is 3
\
5 4 <-- Level 2: rightmost is 4
Looking from the right side, at level 0 we see node 1, at level 1 we see node 3 (3 is to the right of 2), and at level 2 we see node 4 (4 is to the right of 5). Thus, the output is [1, 3, 4].
root = [1,2,3,4,null,null,null,5][1,3,4,5]The tree structure is: 1 <-- Level 0: rightmost is 1 / 2 3 <-- Level 1: rightmost is 3 / 4 <-- Level 2: rightmost is 4 / 5 <-- Level 3: rightmost is 5
Even though nodes 4 and 5 are on the left branch, they are the only nodes (and hence the rightmost) at their respective levels. The output is [1, 3, 4, 5].
root = [1,null,3][1,3]The tree has only two nodes: root 1 and its right child 3. At level 0, the rightmost is 1. At level 1, the only node is 3, so it is the rightmost. The output is [1, 3].
Constraints