代码随想录——第十四天

第六章 二叉树 part02

226.翻转二叉树 (优先掌握递归)

这道题目 一些做过的同学 理解的也不够深入,建议大家先看我的视频讲解,无论做过没做过,都会有很大收获。

题目链接/文章讲解/视频讲解:https://programmercarl.com/0226.%E7%BF%BB%E8%BD%AC%E4%BA%8C%E5%8F%89%E6%A0%91.html

class Solution {

    public TreeNode invertTree(TreeNode root) {

        if(root == null){

            return root;

        }

        TreeNode temp = root.left;

        root.left = root.right;

        root.right = temp;

        root.left = invertTree(root.left);

        root.right = invertTree(root.right);

        return root;

    }

}

101. 对称二叉树 (优先掌握递归)

先看视频讲解,会更容易一些。

题目链接/文章讲解/视频讲解:https://programmercarl.com/0101.%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91.html 

class Solution {

    public boolean isSymmetric(TreeNode root) {

        return symmetric(root.left, root.right);

    }

    public boolean symmetric(TreeNode left, TreeNode right){

        if(left == null && right != null) return false;

        if(left != null && right == null) return false;

        if(left != null && right != null && left.val != right.val) return false;

        if(left == null && right == null) return true;

        boolean outside = symmetric(left.left, right.right);

        boolean inside = symmetric(left.right, right.left);

        return outside && inside;

    }

}

104.二叉树的最大深度 (优先掌握递归)

什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。

大家 要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。

题目链接/文章讲解/视频讲解: https://programmercarl.com/0104.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6.html 

class Solution {

    public int maxDepth(TreeNode root) {

        if(root == null) return 0;

        int hl = maxDepth(root.left);

        int hr = maxDepth(root.right);

        return 1 + Math.max(hl, hr);  

    }

}

return 1 + (hl > hr ? hl : hr);//括号

111.二叉树的最小深度 (优先掌握递归)

先看视频讲解,和最大深度 看似差不多,其实 差距还挺大,有坑。

题目链接/文章讲解/视频讲解:https://programmercarl.com/0111.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E6%B7%B1%E5%BA%A6.html

class Solution {

    public int minDepth(TreeNode root) {

        if(root == null) return 0;

        if(root.left == null && root.right != null) return 1 + minDepth(root.right);

        if(root.left != null && root.right == null) return 1 + minDepth(root.left);

        return 1 + Math.min(minDepth(root.right), minDepth(root.left));  

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容