This question evaluates understanding of binary tree structures and traversal techniques, specifically reasoning about the right-side view by depth, along with the ability to analyze time and space complexity.
You are given the root of a binary tree.
From the right side of the tree, at each depth you can see exactly one node: the rightmost node at that depth.
Write a function that returns a list of the values of the nodes visible when looking at the tree from the right side, ordered from top to bottom.
rightSideView(root: TreeNode) -> List[int]
Where TreeNode is defined as:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
Consider this binary tree:
1
/ \
2 3
\ \
5 4
The right-side view is:
[1, 3, 4]
Explain the algorithm you would use, including its time and space complexity. You may use either breadth-first search (BFS) or depth-first search (DFS).