You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The solution correctly implements a BFS traversal to capture the right side view.
The time and space complexity are optimal.
The code is concise and uses a single loop to handle level-order traversal.
Areas for improvement:
It would be better to add comments to explain the logic, especially the use of size to track the current level.
The typical approach (as in the reference solution) uses an inner for loop to process each level. While your approach is correct, it is less common and might be harder for some readers to understand. Consider using the nested loop for clarity.
There is a minor issue: the initial size is set to q.size() which is 1. But what if the root is null? You handle that by returning an empty list. So that is correct.
However, in the code, you have: int size = q.size();
This is done outside the loop. Then inside the loop, you update size only when you finish a level. This is correct. But note that the variable size is being reused for the next level. This is acceptable.
Alternatively, you can use a nested loop to make the level processing explicit:
while (!q.isEmpty()) {
int levelSize = q.size();
for (int i=0; i<levelSize; i++) {
TreeNode curr = q.poll();
if (i == levelSize-1) list.add(curr.val);
// add children
}
}
This might be clearer.
Also, note that in your code, when you add the children, you are adding both left and right. This is correct.
Overall, the solution is correct. However, for better readability and maintainability, consider using the nested loop approach.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.