zoukankan      html  css  js  c++  java
  • 剑指 Offer 28. 对称的二叉树

    题意

    如题所示

    思路

    • 分类讨论
      • 1⃣️ 左右子树都为空是对称的
      • 2⃣️ 只有左子树或者右子树的时候不是对称的
      • 3⃣️ 对称位置上的值要相等,而且它的左孩子和右孩子也要是对称的
    • 有了上面的分类讨论,就可以根据这个直接写代码了

    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)
    
    如有转载,请注明出处QAQ
  • 相关阅读:
    【NOIP2018】游记
    题解 P1441 【砝码称重】
    题解 P3128 【[USACO15DEC]最大流Max Flow】
    题解 P1949 【聪明的打字员_NOI导刊2011提高(10)】
    题解 P1966 【火柴排队】
    题解 P1895 【数字序列】
    topcoder做题
    1149E
    hdu 6589
    hdu 6579
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/15177444.html
Copyright © 2011-2022 走看看