题目描述
请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
核心代码实现
/*
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){
if(pRoot == null){
return true;
}
return isSame(pRoot.left, pRoot.right);
}
//递归解法,自行绘制一棵对称二叉树进行辅助理解
boolean isSame(TreeNode lRoot, TreeNode rRoot){
if(lRoot == null && rRoot == null){
return true;
}else if(lRoot == null || rRoot == null){
return false;
}
if(lRoot.val != rRoot.val){
return false;
}else{
return isSame(lRoot.left, rRoot.right) && isSame(lRoot.right, rRoot.left);
}
}
/*
//非递归解法
LinkedList<TreeNode> lList = new LinkedList<>();
LinkedList<TreeNode> rList = new LinkedList<>();
lList.add(pRoot.left);
rList.add(pRoot.right);
while(!lList.isEmpty() && !rList.isEmpty()){
TreeNode lNode = lList.poll();
TreeNode rNode = rList.poll();
if(lNode == null && rNode == null){
continue;
}else if(lNode == null || rNode == null){
return false;
}else if(lNode.val != rNode.val){
return false;
}
lList.add(lNode.left);
lList.add(lNode.right);
rList.add(rNode.right);
rList.add(rNode.left);
}
return lList.isEmpty() && rList.isEmpty();
}
*/
}