剑指 Offer 28. 对称的二叉树

时间:2021-08-23 23:05:23   收藏:0   阅读:17

题意

如题所示

思路

Java 代码

class Solution {
    public boolean judgeSymmetric(TreeNode r1, TreeNode r2) {
        if(r1 == null && r2 == null) return true;
        if(r1 == null && r2 != null) return false;
        if(r1 != null && r2 == null) return false;
        return r1.val == r2.val && judgeSymmetric(r1.left, r2.right) && judgeSymmetric(r1.right, r2.left);
    }
    
    public boolean isSymmetric(TreeNode root) {
        return judgeSymmetric(root, root);
    }
}

Python 代码

class Solution:
    def judge(self, root1, root2):
        if not root1 and not root2:
            return True
        if not root1 or not root2:
            return False
        return root1.val == root2.val and self.judge(root1.left, root2.right) and self.judge(root1.right, root2.left)

    def isSymmetric(self, root: TreeNode) -> bool:
        return self.judge(root, root)

原文:https://www.cnblogs.com/MartinLwx/p/15177444.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!