代码随想录算法训练营,9月10日 | 226.翻转二叉树,101. 对称二叉树,104.二叉树的最大深度,111.二叉树的最小深度

226.翻转二叉树
题目链接:226.翻转二叉树
文档讲解︰代码随想录(programmercarl.com)
视频讲解︰翻转二叉树
日期:2024-09-10

想法:按照前序遍历的思路,先翻转再递归左右。
Java代码如下:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return root;
        }
        swap(root);
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public void swap(TreeNode root){
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
}

总结:swap参数的设置出了点错。

101. 对称二叉树
题目链接:101. 对称二叉树
文档讲解︰代码随想录(programmercarl.com)
视频讲解︰对称二叉树
日期:2024-09-10

想法:返回条件:左节点为空,右节点不为空,不对称;左不为空,右为空,不对称;左右都为空,对称;左右都不为空,比较节点数值,不相同就return false。单层逻辑:比较外侧内侧是否对称
Java代码如下:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left, root.right);
    }

    private boolean compare(TreeNode left, TreeNode right) {

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

        if (left == null && right == null) {
            return true;
        }
        if (left.val != right.val) {
            return false;
        }
        boolean compareOutside = compare(left.left, right.right);
        boolean compareInside = compare(left.right, right.left);
        return compareOutside && compareInside;
    }
}

总结:递归三部曲的熟练运用。

104.二叉树的最大深度
题目链接:104.二叉树的最大深度
文档讲解︰代码随想录(programmercarl.com)
视频讲解︰二叉树的最大深度
日期:2024-09-10

想法: 二叉树深度是根节点到该节点的最长节点数,高度是该节点到叶子节点的最长节点数。
三部曲:确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度;如果为空节点的话,就返回0;先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值再+1
Java代码如下:

//递归
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

111.二叉树的最小深度
题目链接:111.二叉树的最小深度
文档讲解︰代码随想录(programmercarl.com)
视频讲解︰二叉树的最小深度
日期:2024-09-10

想法:确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度;如果为空节点的话,就返回0;先求它的左子树的深度,再求右子树的深度,最后取左右深度最小的数值再+1
Java代码如下:

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        if (root.left == null) {
            return rightDepth + 1;
        }
        if (root.right == null) {
            return leftDepth + 1;
        }
        return Math.min(leftDepth, rightDepth) + 1;
    }
}

总结:要注意判断左子树或者右子树为空的情况,要不然深度输出就是1了。

posted @ 2024-09-10 21:08  漪欢酒  阅读(23)  评论(0)    收藏  举报