I have code for calculating max depth using BFS, which works fine, but I couldn't figure out why it fails if I replaced for i in range(len(q)):
with for i in q:
.
The code below works correctly and passes all tests:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
q = list([root])
level = 0
while q:
for i in range(len(q)):
node = q.pop(0)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
level += 1
return level
But the code below with for i in q
fails some tests:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
q = list([root])
level = 0
while q:
for i in q: # the only difference
node = q.pop(0)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
level += 1
return level
for i in range(len(q)):
and for i in q:
provide exactly the same number of iterations or do I misunderstand something? I don't understand why it would make any difference... Any ideas?
Thank you.