Question
101. 对称二叉树
Ideas
核心思想:同时遍历两棵子树 首先排除空节点 然后比较两个子树的值 最后去子树的子树比较 需要注意: 左子树的左边是右子树的右边 左子树的右边是左子树的左边 有点绕
Code
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.compare(root.left, root.right)
def compare(self, left, right):
if left == None and right != None: return False
elif left != None and right == None: return False
elif left == None and right == None: return True
elif left.val != right.val: return False
outside = self.compare(left.left, right.right)
inside = self.compare(left.right, right.left)
isSame = outside and inside
return isSame
|