如题,当使用队列迭代方法求解时,为什么不可以把两个root点按顺序同时放在队列中,必须要用()放在队列中?
错解:
class Solution(object):
def mergeTrees(self, root1, root2):
if not (root1 and root2):
return root1 if root1 else root2
queue=[root1,root2]
while queue:
p=queue.pop()
q=queue.pop()
p.val+=q.val
if p.left and q.left:
queue.append(p.left)
queue.append(q.left)
elif q.left:
p.left=q.left
if p.right and q.right:
queue.append(p.right)
queue.append(q.right)
elif q.right:
p.right=q.right
return root1
正解:
class Solution(object):
def mergeTrees(self, root1, root2):
if not (root1 and root2):
return root1 if root1 else root2
queue=[(root1,root2)]
while queue:
p,q=queue.pop()
p.val+=q.val
if p.left and q.left:
queue.append((p.left,q.left))
elif q.left:
p.left=q.left
if p.right and q.right:
queue.append((p.right,q.right))
elif q.right:
p.right=q.right
return root1