对称二叉树

题目:
给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/
2 2
/ \ /
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

1

/
2 2
\
3 3

思路:递归

package edu.LeetCode.对称的树;

public class Solution {
    //判断是否是对称的树
    public boolean isSymmetric(TreeNode root){
        return isMirror(root,root);
    }
    //写一个函数判断此树是否是镜像对称(每个树的右子树是否与其左子树对称)
    private boolean isMirror(TreeNode r1, TreeNode r2) {
        //都为空则一定是对称的
        if(r1 == null && r2 == null){
            return true;
        }
        //只有一个为空则返回false
        if(r1 == null || r2 == null){
            return false;
        } else{
            //判断当前节点的值是否相等以及右子树与左子树是否相等
            return (r1.val == r2.val)&&isMirror(r1.left,r2.right)&& isMirror(r1.right,r2.left);
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode r1 = new TreeNode(2);
        TreeNode r2 = new TreeNode(2);
        TreeNode r3 = new TreeNode(3);
        TreeNode r4 = new TreeNode(4);
        TreeNode r5 = new TreeNode(4);
        TreeNode r6 = new TreeNode(3);

        root.left = r1;
        root.right = r2;
        r1.left = r3;
        r1.right = r4;
        r2.left = r5;
        r2.right = r6;

        Solution s = new Solution();
        System.out.println(s.isSymmetric(root));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值