# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution:
defisSymmetric(self, root: TreeNode) -> bool: return self.isMirror(root,root) defisMirror(self, l: TreeNode, r: TreeNode) -> bool: ## l,r是两个指针,每次检查两个指针的值是否相同,如相等再判断左右子树是否对称 ## 递归的终止天剑是两个节点都为空 ## 或者两个节点有一个为空 if l == Noneand r == None: returnTrue if l == Noneor r == None: returnFalse ## 两个根节点具有相同的值 ## 每个树的右子树与另一个树的左子树镜像对称 return l.val == r.val and self.isMirror(l.left,r.right) and self.isMirror(l.right,r.left)
迭代 O(n) O(n)
classSolution(object): defisSymmetric(self, root): ## 如果树为空,或者左子树右子树都为空,那么这也是对称的 ifnot root ornot (root.left or root.right): returnTrue # 用队列保存节点,先将根节点的左子树根节点和右子树根节点放到队列中 queue = [root.left,root.right] while queue: # 从队列中取出两个节点,再比较这两个节点 left = queue.pop(0) right = queue.pop(0) # 如果两个节点都为空就继续循环,两者有一个为空就返回false ifnot (left or right): continue ifnot (left and right): returnFalse if left.val!=right.val: ## 如果两个值不相同,则不对称 returnFalse # 将左节点的左孩子, 右节点的右孩子放入队列 queue.append(left.left) queue.append(right.right) # 将左节点的右孩子,右节点的左孩子放入队列 queue.append(left.right) queue.append(right.left) returnTrue