26、判断二叉树是否为对称的二叉树——剑指offer

判断二叉树是否为对称的二叉树

问题描述:判断二叉树是否为对称的二叉树,如果一棵二叉树和其镜像二叉树一样,那么它就是对称的

    首先考察基本功,二叉树镜像、前序遍历等,我们可以写一个镜像二叉树的函数,然后判断两棵二叉树是否一样,如果一样则说明正确,二叉树镜像的函数在上一篇写过了,这里不赘述了,这里采用一种特殊的遍历方法的方法

    本方法思想:定义一个前序遍历和对称的前序遍历方法,如果遍历结果一样则对称(要考虑到空指针。。),不考虑空指针会出错,比如一个树是7.left=7;另一个是7.right=7,无论怎么遍历结果都一样,如果考虑空指针则可以正确判断

持续更新...

代码附下

Java实现:

package 判断二叉树是否对称;
/**
 * 如果一个二叉树和它的镜像一样,就是对称二叉树
 * @author user
 *思路1:将二叉树镜像
 *思路2:定义一个前序遍历和对称的前序遍历方法
 *如果遍历结果一样则对称(要考虑到空指针。。)
 *不考虑空指针会出错,比如一个树是7.left=7;另一个是7.right=7
 *无论怎么遍历结果都一样
 */

二叉树的数据结构:

public class BinaryTree {
    int val;
    BinaryTree left = null;
    BinaryTree right = null;
    public BinaryTree(int val) {
        this.val = val;
    }
}

 

public class Test {
    public static boolean isSymmetrical(BinaryTree root1, BinaryTree root2) {
        if (root1 == null && root2 == null) {
            return true;
        }
        if (root1 == null || root2 == null) {
            return false;
        }
        if (root1.val != root2.val) {
            return false;
        }
        //判断A的左边和B的右边是否相等,判断A的右边和B的左边是否相等,都相等就满足
        return isSymmetrical(root1.left, root2.right) && isSymmetrical(root1.right, root2.left);
    }

    public static void main(String[] args) {
        BinaryTree rootA = new BinaryTree(8);
        rootA.left = new BinaryTree(9);
        rootA.right = new BinaryTree(9);
        // rootA.left.left=new BinaryTree(9);
        // rootA.left.right=new BinaryTree(2);
        // rootA.left.right.left=new BinaryTree(4);
        // rootA.left.right.right=new BinaryTree(7);
        System.out.println(isSymmetrical(rootA, rootA));//测试

    }
}

持续更新...欢迎赞赏!

主页:https://blog.csdn.net/ustcer_93lk/article/details/80374008

如果有问题,欢迎大家留言,有更好的方法也期待大家告知。

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值