Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
1. 递归方法
要保证symmetric就必须保证root的左右节点要是相同的。左右节点的所有子孙,都是其左节点的左儿子要等于右节点的又儿子,左节点的右儿子要等于右节点的左儿子,因此可以递归。
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode lt, TreeNode rt) {
if (lt == null && rt == null) {
return true;
}
if (lt == null && rt != null || lt != null && rt == null || lt.val != rt.val) {
return false;
}
return isSymmetric(lt.left, rt.right) && isSymmetric(lt.right, rt.left);
}
2. 遍历
使用层续遍历,判断每一层是否对称即可
def isSymmetric(self, root):
if root is None:
return True
q = []
q.append(root)
level_num = 1
while level_num != 0:
i = 0
while i < level_num:
node = q[i]
i = i + 1
if node is None:
continue
q.append(node.left)
q.append(node.right)
start = 0
end = level_num - 1
while start < end:
lt = q[start]
rt = q[end]
if lt is not None and rt is not None:
if lt.val != rt.val:
return False
elif (lt is None and rt is not None) or (lt is not None and rt is None):
return False
start = start + 1
end = end - 1
q = q[level_num: ]
level_num = len(q)
return True