Back to course home
0% completed
Vote For New Content
You don't need to check level size.
vipulmeh23
Jun 17, 2024
After the for loop iterates through the length of the level, just add the node that you get after popleft. Extra logic, does not make much sense.
from collections import deque #class TreeNode: # def __init__(self, val): # self.val = val # self.left, self.right = None, None class Solution: def traverse(self, root): result = [] # List[int] if root is None: return result # TODO: Write your code here q = deque() q.append(root) while q: level_size = len(q) for _ in range(level_size): node = q.popleft() if node.left: q.append(node.left) if node.right: q.append(node.right) result.append(node.val) return result
0
0
Comments
Comments
On this page