101. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树[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
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
递归法
子树p和q的值相等,而且p的左子树和q的右子树对称,p的右子树和q的左子树对称
# 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
"""
return True if not root else self.symmetric(root.left, root.right)
# 判断左右子树是否对称
def symmetric(self, p, q):
if not p and not q: # 均为空
return True
if not p or not q: # 一个为空一个不为空
return False
# 两节点值相同,且p左子树与q右子树对称,p右子树与q左子树对称是为真
return p.val == q.val and self.symmetric(p.left, q.right) and self.symmetric(p.right, q.left)
迭代法
用一个栈来维护节点的插入,注意插入顺序是p.left, q.right, p.right, q.left,因为弹出是是分别比较左右两边的子树是否对称。
# 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 not root:
return True
stack = []
p, q = root.left, root.right
stack.append(p)
stack.append(q)
while stack:
p = stack.pop()
q = stack.pop()
if not p and not q: # p和q均为空,对称
continue
if not p or not q: # p和q有一个为空,不对称
return False
if p.val != q.val: # p和q值不相等,不对称
return False
stack.append(p.left)
stack.append(q.right)
stack.append(p.right)
stack.append(q.left)
return True

浙公网安备 33010602011771号