Leetcode剑指Offer刷题 - 第七天

Leetcode剑指Offer刷题 - 第七天,第1张

Leetcode剑指Offer刷题 - 第七天

 Leetcode剑指Offer刷题指南:

Leetcode剑指Offer刷题-学习计划目录_DEGv587的博客-CSDN博客

 剑指 Offer 26. 树的子结构

解法递归

class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (A == null || B == null) {
            return false;
        }
        return dfs(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }

    private boolean dfs(TreeNode A, TreeNode B) {
        if (B == null) return true;
        if (A == null) return false;

        return A.val == B.val && dfs(A.left, B.left) && dfs(A.right, B.right);
    }
}

剑指 Offer 27. 二叉树的镜像

解法:递归

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) return null;

        TreeNode tmp = root.left;
        root.left = mirrorTree(root.right);
        root.right = mirrorTree(tmp);

        return root;
    }
}

剑指 Offer 28. 对称的二叉树

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;

        return dfs(root.left, root.right);
    }

    private boolean dfs(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) return true;
        if (root1 == null || root2 == null) return false;

        return root1.val == root2.val && dfs(root1.left, root2.right) && dfs(root1.right, root2.left);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5716952.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存