给你一个二叉树的根节点 root , 检查它是否轴对称。
广度优先算法使用队列来实现遍历,将二叉树的左右子树分别入队出队,不同点在于左子树入队顺序先左后右,右子树入队先右后左。比对每个节点是否一样,返回对比结果,
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> leftTreeQueue=new LinkedList<>();
Queue<TreeNode> rightTreeQueue=new LinkedList<>();
if (root.left==null&&root.right==null){
return true;
}
TreeNode leftTree=root.left;
TreeNode rightTree=root.right;
leftTreeQueue.offer(leftTree);
rightTreeQueue.offer(rightTree);
while (!leftTreeQueue.isEmpty()){
if (!rightTreeQueue.isEmpty()){
TreeNode leftNode = leftTreeQueue.poll();
TreeNode rightNode = rightTreeQueue.poll();
if (leftNode==null&&rightNode==null){
continue;
}else if (leftNode==null||rightNode==null){
return false;
}else {
if (leftNode.val!=rightNode.val){
return false;
}
}
leftTreeQueue.offer(leftNode.left);
leftTreeQueue.offer(leftNode.right);
rightTreeQueue.offer(rightNode.right);
rightTreeQueue.offer(rightNode.left);
}
}
return leftTreeQueue.isEmpty()&&rightTreeQueue.isEmpty();
}