【问题标题】:Two ways of finding symmetric trees through recurrsion通过递归找到对称树的两种方法
【发布时间】:2020-01-29 03:32:19
【问题描述】:

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))

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

【问题讨论】:

    标签: python-3.x recursion tree binary-tree


    【解决方案1】:

    糟糕,我得到了答案。

          1
         / \
        2   2
         \   \
         3    3
    

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

    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))
    

    【讨论】:

      猜你喜欢
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 2016-07-13
      • 2017-01-08
      • 1970-01-01
      相关资源
      最近更新 更多