超爱笑的 2021-09-21 15:38 采纳率: 100%
浏览 22
已结题

做了一道leecode题(617题 合并二叉树),有一点不太明白

img

如题,当使用队列迭代方法求解时,为什么不可以把两个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

  • 写回答

1条回答 默认 最新

  • CSDN专家-sinJack 2021-09-21 15:51
    关注

    合并二叉树,是需要将两颗树对应的节点值进行相加。
    所以将对应位置作为一个整体放入队列中。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月29日
  • 已采纳回答 9月21日
  • 创建了问题 9月21日