leetcode 101. 对称二叉树 简单 树

题目:
## 标题

分析:先理解好镜像的概念再去思考怎么做题。这道题还是比较容易想到用递归的,比较两棵树,剩下的就是思考递归怎么结束
有几个条件,1.两棵子树都是空的,2.有一棵子树是空的,3.两个树节点的值不相等

代码:

/**
 * 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;
        }
        return isSymmetric(root.left,root.right);
    }
    boolean isSymmetric(TreeNode n1, TreeNode n2){
        if(n1 == null && n2 == null){
            return true;
        }
        //有一个为空了说明左右长度不等,一定不是镜像
        if(n1 == null || n2 == null){
            return false;
        }
        if(n1.val != n2.val){
            return false;
        }
        return isSymmetric(n1.left,n2.right) && isSymmetric(n1.right, n2.left);
    }
}

在这里插入图片描述
在这里插入图片描述

发布了134 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_40208575/article/details/105184629