【问题标题】:what is the difference between my code and the solution that checks if two binary trees are identical?我的代码和检查两个二叉树是否相同的解决方案有什么区别?
【发布时间】:2021-05-14 11:31:21
【问题描述】:

我正在编写代码来检查两棵树是否相同,但我需要帮助来确定我编写的代码与实际解决方案之间有什么不同。

这是我的代码:

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p or not q:
            return False
        if not p and not q:
            return True
        if p.val != q.val:
            return False

        return self.isSameTree(p.right,q.right) and self.isSameTree(p.left,q.left)

这是正确的代码:

class Solution:
    def isSameTree(self, p, q):
        
        if not p and not q:
            return True

        if not q or not p:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.right, q.right) and \
               self.isSameTree(p.left, q.left)

【问题讨论】:

  • if not p and not q: 在你的版本中永远不会是真的,因为之前的if 已经处理了这个(更强的)条件。顺序很重要。

标签: python tree


【解决方案1】:

条件 if not p or not q: 包含 p 和 q 为 None 的情况,在这种情况下,当您在代码中返回 False 时,两棵树显然是相同的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    相关资源
    最近更新 更多