【发布时间】: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