Conversation
Right Side View of a tree (Problem1.py)Your solution has a good structure and you've correctly identified that a level-order traversal (BFS) is suitable for this problem. However, there are a few critical issues that need to be addressed:
Here is a corrected version of your code: from collections import deque
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
result = []
levelQueue = deque([root])
while levelQueue:
level_size = len(levelQueue)
for i in range(level_size):
node = levelQueue.popleft()
# If it's the last node in the current level, add to result
if i == level_size - 1:
result.append(node.val)
# Add left and right children if they exist
if node.left:
levelQueue.append(node.left)
if node.right:
levelQueue.append(node.right)
return resultWait, note: the above corrected code uses the last node in the level (i == level_size-1) instead of the first. Why? Because in a standard BFS where we add left first and then right, the last node in the level will be the rightmost. Alternatively, if you add right first and then left, the first node would be the rightmost. So both approaches are valid. But your original code used the first node (i=0) and added right first then left. That is correct. However, you did not handle null nodes. So the corrected code for your approach would be: from collections import deque
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
if i == 0:
result.append(node.val)
# Add right child first, then left
if node.right:
queue.append(node.right)
if node.left:
queue.append(node.left)
return resultThis should work. But note: the common approach is to add left first and then right, and take the last node in the level. Your approach is valid too. However, your original code did not check for null when adding children. So you must add those checks.
VERDICT: NEEDS_IMPROVEMENT Cousins in Tree (Problem2.py)Strengths:
Areas for Improvement:
How to fix:
Revised approach:
Example code structure: VERDICT: NEEDS_IMPROVEMENT |
No description provided.