美文网首页
【剑指28】对称的二叉树

【剑指28】对称的二叉树

作者: 浅浅星空 | 来源:发表于2019-07-22 19:47 被阅读0次

    题目描述

    请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

    分析

        boolean isSymmetrical(TreeNode pRoot) {
            return isSymmetricalCore(pRoot, pRoot);
        }
    
        public boolean isSymmetricalCore(TreeNode root1, TreeNode root2) {
            if (root1 == null && root2 == null) return true;
            if (root1 == null || root2 == null) return false;
            if (root1.val != root2.val) return false;
            return isSymmetricalCore(root1.left, root2.right) && isSymmetricalCore(root1.right, root2.left);
        }
    

    2.比较左子树和右子树是否相同

        boolean isSymmetrical(TreeNode pRoot) {
            if (pRoot == null) return true;
            return isSymmetricalCore(pRoot.left, pRoot.right);
        }
    
        public boolean isSymmetricalCore(TreeNode root1, TreeNode root2) {
            if (root1 == null && root2 == null) return true;
            if (root1 == null || root2 == null) return false;
            if (root1.val != root2.val) return false;
            return isSymmetricalCore(root1.left, root2.right) && isSymmetricalCore(root1.right, root2.left);
        }
    

    相关文章

      网友评论

          本文标题:【剑指28】对称的二叉树

          本文链接:https://www.haomeiwen.com/subject/gqrglctx.html