题目:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
思路:
1)首先想到的一定是用递归。比较关键的一点是,判断对称二叉树要比较的是哪两个子树的关系,不是单纯“左子树=右子树”。所以要比较的是两个树,参数自然也是左子树节点和右子树节点。
两种情况需要考虑,一个是有节点为空的情况,一个是左右节点都不为空的情况。
2)迭代法。根节点的左右节点分别入队列比较,不同的话就直接返回false。相同就继续比较。
代码:
1)
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root: return True
def comp (left, right):
if not left and not right: return True ##左右都为空
elif not left and right : return False ##左空,右不空
elif not right and left : return False ## 左不空,右空
elif right.val != left.val: return False ## 左右不为空,但是左右值不相同
return comp(left.left,right.right) and comp(left.right,right.left)
return comp(root.left, root.right)
2)
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue = collections.deque()
if not root: return True
queue.append(root.left)
queue.append(root.right)
while queue:
leftNode = queue.popleft()
rightNode = queue.popleft()
if not leftNode and not rightNode: continue
if (not leftNode and rightNode) or (leftNode and not rightNode) or leftNode.val!=rightNode.val: return False
queue.append(leftNode.left)
queue.append(rightNode.right)
queue.append(leftNode.right)
queue.append(rightNode.left)
return True