题解 | #对称的二叉树#
对称的二叉树
http://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
利用层次遍历判断每一层是否对称
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
boolean isSymmetrical(TreeNode pRoot) {
LinkedList<TreeNode> list = new LinkedList<>();
list.add(pRoot);
if(pRoot==null){
return true;
}
while(!list.isEmpty()){
int curSize = list.size();
LinkedList<Integer> temp = new LinkedList<>();
while(curSize>0){
TreeNode node = list.poll();
if(node.left!=null){
list.add(node.left);
temp.add(node.left.val);
}else{
temp.add(null);
}
if(node.right!=null){
list.add(node.right);
temp.add(node.right.val);
}else{
temp.add(null);
}
curSize--;
}
for(int i=0;i<Math.abs(temp.size()/2);i++){
if(temp.get(i)!=temp.get(temp.size()-1-i)){
return false;
}
}
temp.clear();
}
return true;
}
}