- 节点
- 距离、高度、值
- 结构
- 序列(前、中、后)
- 打印
剑指Offer 28. 【对称】的二叉树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
### 1212 递归(44 ms,14.9 MB)
def isSymmetric(self, root: TreeNode) -> bool:
def recur(L, R):
# 终止条件:若当前左、右子节点均为空,表示二者对称,返回True
if not L and not R: return True
# 若只有左子节点为空 或 只有右子节点为空 或 左、右子节点不相等,则此(子)树不对称,返回False
if not L or not R or L.val != R.val: return False
# 若当前左、右子节点对称,则继续递归判断下面的左、右子树是否对称
return recur(L.left, R.right) and recur(L.right, R.left)
return recur(root.left, root.right) if root else True # 若根节点为空,则直接返回True,否则开始递归判断
### 0122 迭代(36 ms,15.1 MB)
def isSymmetric(self, root: TreeNode) -> bool:
# 若根节点为空,则对称(or 根节点的左右子树均为空)
if not root:
return True
# 先存放根节点的左、右子树
queue = [root.left, root.right]
while queue:
# 左、右子树依次出队
l = queue.pop(0)
r = queue.pop(0)
# 若两棵子树均为空,则对称
if not l and not r:
continue
# 若只有其中一棵子树为空 or 当前对称两个节点的值不相等,则不对称
elif not l or not r or l.val != r.val:
return False
# 左、右子树对称配对入栈_1
queue.append(l.left)
queue.append(r.right)
# 左、右子树对称配对入栈_2
queue.append(l.right)
queue.append(r.left)
return True # 若所有对称节点都匹配,则是对称树
### 0122 递归(36 ms,15.2 MB)
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
def dfs(l, r):
if not l and not r:
return True
elif not l or not r or l.val != r.val:
return False
# 继续判断左、右子树是否对称
return dfs(l.left, r.right) and dfs(l.right, r.left)
return dfs(root.left, root.right)