【LeetCode】面试题28. 对称的二叉树
题目:
思路:
1、递归处理子问题,判断某个树是否对称只需要判断它的左右子树是否对称,而判读两个树是否对称需要判断: 根结点是否相等 && A.left和B.right是否对称 && A.right和B.left是否对称。判断子树是否对称变成了相同的子问题,递归处理。注意这里的核心是把一颗树是否对称的问题转换成了判断两个树是否对称,从而可以得到相同子问题并递归处理;如果像原问题那样判断一颗树是否对称无法分解成子问题,因为左子树对称并且右子树对称并不能得到该树是对称树,而是左子树和右子树对称才能得到该树对称。
2、广度优先遍历(层次遍历),利用队列实现(双端队列或两个队列)
代码:
Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isMirror(self, A, B):
if A is None and B is None:
return True
if A is None or B is None:
return False
if A.val == B.val:
return self.isMirror(A.left, B.right) and self.isMirror(A.right, B.left)
return False
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
return self.isMirror(root.left, root.right)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
A = [root.left]
B = [root.right]
while A:
a = A.pop()
b = B.pop()
if a is None and b is None:
continue
elif a is None or b is None:
return False
elif a.val != b.val:
return False
else:
A.append(a.left)
A.append(a.right)
B.append(b.right)
B.append(b.left)
return True