判断一棵二叉树是否是对称二叉树
程序员文章站
2024-01-15 12:46:16
...
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
//判断一棵树是否为对称二叉树
public boolean isSymmetric(TreeNode root) {
if(root==null||(root.left==null&&root.right==null))
return true;
return isSymmetricCheck(root,root);
}
//递归调用实现
public boolean isSymmetricCheck(TreeNode x,TreeNode y){
if(x==null&&y==null) return true;
if((x!=null&&y==null)||(x==null&&y!=null)) return false;
return (x.val==y.val)&&isSymmetricCheck(x.left,y.right)&&isSymmetricCheck(x.right,y.left);
}
public static void main(String[]args){
//System.out.println("Hello Wolrd!");
TreeNode root=new TreeNode(1);
root.left=new TreeNode(2);
root.right=new TreeNode(2);
root.left.left=new TreeNode(3);
root.right.right=new TreeNode(3);
Solution s=new Solution();
System.out.println(s.isSymmetric(root));
}
}