一、题目描述
给定一个二叉树,检查它是否是镜像对称的。
二、分析
满足镜像对称的条件:
- 必须是俩个结点(t1,t2);
- t1,t2的值必须相等;
- t1的左结点和t2的右结点必须同时为空或者同时有值;
- t2的右结点和t1的左结点必须同时为空或者同时有值;
三、解法
1.使用递归
public boolean isSymmetric(TreeNode root) {
return isTrue(root,root);
}
private static boolean isTrue(TreeNode t1, TreeNode t2){
// 递归的结束条件
if (t1 == null && t2 == null)
return true;
//
if (t1 == null || t2 == null)
return false;
// 先要满足当前俩个结点的值相等
return t1.val == t2.val && isTrue(t1.left,t2.right) && isTrue(t1.right,t2.left);
}
2.非递归(迭代)
public boolean isSymmetric1(TreeNode root) {
// 使用链表存储左右子结点
LinkedList<TreeNode> nodes = new LinkedList<>();
// 将根结点加入俩次,便于第一次比较
nodes.add(root);
nodes.add(root);
//
while (!nodes.isEmpty()){
TreeNode t1 = nodes.removeFirst();
TreeNode t2 = nodes.removeFirst();
//
if (t1 == null && t2 == null)
continue;
if (t1 == null || t2 == null)
return false;
if (t1.val != t2.val)
return false;
// 加入左结点的左结点
nodes.add(t1.left);
// 加入右结点的右结点
nodes.add(t2.right);
// 加入左结点的右结点
nodes.add(t1.right);
// 加入右结点的左结点
nodes.add(t2.left);
}
return true;
}