27.剑指Offer-对称的二叉树
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
boolean isSymmetrical(TreeNode pRoot) {
if (pRoot == null)
return true;
return isSymmetrical(pRoot.left, pRoot.right);
}
boolean isSymmetrical(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null)
return true;
if (t1 == null || t2 == null)
return false;
if (t1.val != t2.val)
return false;
return isSymmetrical(t1.left, t2.right) && isSymmetrical(t1.right, t2.left);
}
判断第一个值是否相等,只要遇到一个不相等的就是false。判断根节点的左子树的右节点和右子树的左节点是否相同,左子树的左节点和右子树的右节点是否相同。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
if(pRoot==null){
return true;
}
return subtrue(pRoot.left,pRoot.right);
}
boolean subtrue(TreeNode LRoot,TreeNode RRoot){
if(LRoot==null&&RRoot==null){
return true;
}else if(LRoot!=null&&RRoot!=null){
if(LRoot.val==RRoot.val){
return subtrue(LRoot.right,RRoot.left)&&subtrue(LRoot.left,RRoot.right);
}else{
return false;
}
}else{
return false;
}
}
}