- 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
非递推方法
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);//加两次,每次判断两个
while(!q.isEmpty()){
TreeNode now1 = q.poll();
TreeNode now2 = q.poll();
//if(now1 != now2) return false;
//上面这句是正常思路,但是其实应当判断是否都为null,一旦分支不同,结果自然不同
if(now1 == null && now2 == null) continue;//不能直接返回true
if(now1 == null || now2 == null) return false;
if(now1.val != now2.val ) return false;
//if(now1 != now2) return false;//这样写就不对了,二者的地址是不一定相同的
q.add(now1.left);
q.add(now2.right);
q.add(now1.right);
q.add(now2.left);
}
return true;
}
}
2.递推方法
class Solution {
public boolean isSymmetric(TreeNode root) {
return judge(root, root);
}
boolean judge(TreeNode r1, TreeNode r2){
if(r1 == null && r2 == null) return true;
if(r1 == null || r2 == null) return false;
return r1.val == r2.val &&
judge(r1.left,r2.right) && judge(r1.right, r2.left);
}
}
这个主要利用队列交换的方法
public class Solution {
public void Mirror(TreeNode root) {
if(root == null) return;
LinkedList<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
root = q.poll();
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if(root.left != null) q.add(root.left);
if(root.right != null) q.add(root.right);
}
}
}