• 剑指 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
  • 相关阅读:
    锋利的BFC
    inline和inline-block的间隙问题
    margin和padding的四种写法
    js中Math.round、parseInt、Math.floor和Math.ceil小数取整小结
    使用vscode自动编译less
    redux获取store中的数据
    react显示隐藏动画
    react使用路由
    react中使用fetchjsonp获取数据
    vue兼容到ie9
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/15177444.html
Copyright © 2020-2023  润新知