通过递归寻找对称树的两种方法

Two ways of finding symmetric trees through recurrsion

一个leetcode总和: 给定一棵二叉树,检查它是否是自身的镜像(即围绕其中心对称)。

例如,这个二叉树 [1,2,2,3,4,4,3] 是对称的:

      1
     / \
    2   2
   / \ / \
  3  4 4  3

但是下面的[1,2,2,null,3,null,3]不是:

    1
   / \
  2   2
   \   \
   3    3

正确答案是:-

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if root == None:
            return True
        else:
            return self.Tsolution(root.left, root.right)

    def Tsolution(self, root1, root2):
        if (root1 == None and root2 == None):
            return True
        if root1 == None or root2 == None:
            return False
        else:
            return (root1.val == root2.val and self.Tsolution(root1.left, root2.right) and
            self.Tsolution(root1.right, root2.left))

我的问题是为什么这段代码是错误的?它也在进行 val 检查,但在单独的 if 条件下。

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if root == None:
            return True
        else:
            return self.Tsolution(root.left, root.right)

    def Tsolution(self, root1, root2):
        if (root1 == None and root2 == None):
            return True
        if root1 == None or root2 == None:
            return False
        if root1.val == root2.val:
            return True
        else:
            return (self.Tsolution(root1.left, root2.right) and
            self.Tsolution(root1.right, root2.left))

这让我在上面给出的第二个树示例中出错。

糟糕,我得到答案了。

      1
     / \
    2   2
     \   \
     3    3

当我们到达树的第 2 层时,即 root1.val == 2 和 root2.val == 2 时,我们的函数 returns 在这个条件下为真:

if root1.val == root2.val:
            return True

并且不会进一步深入功能。 因此我们应该包括这个条件以及像这样对左右节点的递归调用

 return (root1.val == root2.val and self.Tsolution(root1.left, root2.right) and
            self.Tsolution(root1.right, root2.left))