您好,我有一个代码来检查树是否为mirror tree。但是,它并没有通过leetcode上的所有测试用例。
我在线上与其他来源进行了核对,但似乎无法弄清楚代码中的错误。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
if root.left and root.right:
return self.is_symmetric(root.left,root.right)
def is_symmetric(self, left, right):
if (left == None and right == None):
return True
if right is None or left is None:
return False
if left.val == right.val:
return True
return self.is_symmetric(left.left,right.right) and self.is_symmetric(left.right,right.left)
谢谢!
答案 0 :(得分:2)
当检查root.left and root.right
的条件为False
时,您的isSymmetric
函数隐式返回None
。相反,它应该继续检查root.left
或root.right
中的一个不是None
,在这种情况下,它应该返回False
;否则root.left
和root.right
均为None
,并且应返回True
。另外,在is_symmetric
函数中,仅因为left.val == right.val
并不意味着左子树与右子树对称,因为它们之下可能有更多子代。当False
时,它应该简单地返回left.val != right.val
:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
if root.left and root.right:
return self.is_symmetric(root.left,root.right)
if root.left or root.right:
return False
return True
def is_symmetric(self, left, right):
if left is None and right is None:
return True
if right is None or left is None or left.val != right.val:
return False
return self.is_symmetric(left.left, right.right) and self.is_symmetric(left.right, right.left)
答案 1 :(得分:0)
检查树是否为镜像树的另一种方法是找到每个节点的路径,然后检查所有路径是否反向:
#include <iostream>
int main() {
std::cout << removeAccents("ᾤκεον") << std::endl;
}
输出:
class Tree:
def __init__(self, **kwargs):
self.__dict__ = {i:kwargs.get(i) for i in ['value', 'left', 'right']}
@staticmethod
def is_reversed(a, b):
return True if not a and not b else all(int(c) == (not int(d)) for c, d in zip(a, b))
def get_paths(self, path = ''):
yield [self.value, path]
yield from getattr(self.right, 'get_paths', lambda _:[])(path+'1')
yield from getattr(self.left, 'get_paths', lambda _:[])(path+'0')
t = Tree(value=31, left=Tree(value=16, left=Tree(value=7), right=Tree(value=24, right=Tree(value=29), left=Tree(value=19))), right=Tree(value=45))
t1 = Tree(value=31, right=Tree(value=16, right=Tree(value=7), left=Tree(value=24, right=Tree(value=19), left=Tree(value=29))), left=Tree(value=45))
"""
31 | 31
/ \ | / \
16 45 | 45 16
/ \ | / \
7 24 | 24 7
/ \ | / \
19 29 | 29 19
"""
_paths1 = dict(list(t.get_paths()))
_paths2 = dict(list(t1.get_paths()))
print(all(Tree.is_reversed(_paths1[i], _paths2[i]) for i in _paths1))