101. Symmetric Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return bfs(root);
}
public boolean bfs(TreeNode root){
if(root==null){
return true;
}
if(root.right==null&&root.left==null){
return true;
}
if(root.right==null||root.left==null){
return false;
}
Queue<TreeNode>queue=new LinkedList<>();
queue.add(root.left);
queue.add(root.right);
while(!queue.isEmpty()){
for(int i=0;i<queue.size()/2;i++){
TreeNode root1=queue.poll();
TreeNode root2=queue.poll();
if(!compareNodes(root1,root2)){
return false;
}
if(root1.left!=null){
queue.add(root1.left);
queue.add(root2.right);
}
if(root1.right!=null){
queue.add(root1.right);
queue.add(root2.left);
}
}
}
return true;
}
public boolean compareNodes(TreeNode root1,TreeNode root2){
if(root1.val!=root2.val){
return false;
}
if(root1.left != null && root2.right == null ||
root2.right != null && root1.left == null ||
root1.right != null && root2.left == null ||
root2.left != null && root1.right == null){
return false;
}
return true;
}
}