对称二叉树(力扣习题)

题目描述:
给定一个二叉树,检查它是否是镜像对称的。
实例:
在这里插入图片描述代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null) {
            return true;
        }
        if(root.left==null&&root.right==null) {
            return true;
        }
        return ismetric(root.left,root.right);
    }
    //把树分为左子树和右子树,看其时候对称
    public boolean ismetric(TreeNode p,TreeNode q) {
        if(p==null&&q==null) {
            return true;
        }
        if(p==null||q==null) {
           return false;
        }
        两个根节点相同,左子树与右子树相同,右子树和左子树相同,构成对称
        return (p.val==q.val&&ismetric(p.left,q.right)&&ismetric(p.right,q.left));
    }
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45755718/article/details/105694249