[LeetCode]101. Symmetric Tree
101. Symmetric Tree
DFS
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def helper(left, right):
if not left and not right:
return True
elif not left or not right:
return False
return helper(left.left, right.right) and helper(left.right, right.left) and left.val == right.val
if not root:
return True
return helper(root.left, root.right)
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def myfunc(n1,n2):
if n1 is None and n2 is None:
return True
if n1 and n2 and n1.val == n2.val:
return myfunc(n1.left,n2.right) and myfunc(n1.right,n2.left)
return False
return myfunc(root, root)
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法