LeetCode 104. Maximum Depth of Binary Tree和111. Minimum Depth of Binary Tree 递归

这篇博客探讨了LeetCode上的两个二叉树问题:104. Maximum Depth of Binary Tree和111. Minimum Depth of Binary Tree。作者详细介绍了如何使用递归方法解决这两个问题,包括题意解析、解题思路和代码实现。在最大深度问题中,重点在于比较左右子树的深度;在最小深度问题中,需要注意当根节点的某一子树为空时的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

题意

给定一个二叉树,求二叉树的深度

注意

二叉树的最大深度定义:是从根节点到叶子结点中的最长路径。
二叉树天然具有递归结构。

思路

先找根节点的左子树深度,再找右子树的深度,比较左右子树深度,返回大的一个
递归的去找,左子树又分左子树右子树。
体会递归的巧妙,一个大问题能够拆分成很多类似大问题解决方案的小问题

代码

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;

        int leftmaxDepth = maxDepth(root->left); //已经获取了左子树的深度
        int rightmaxDepth = maxDepth(root->right);//再获取右子树的深度

        return max(leftmaxDepth,rightmaxDepth)+1; //比较之后选大的,在加上当前结点+1        
    }
};

结果

这里写图片描述

111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

题意

给定一个二叉树,找到二叉树最小的深度

题意

二叉树的最小深度:是从根节点到叶子结点中的最短路径。

思路

若类似104那样做会怎么样。尽管思路大致相同

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;

        int leftmaxDepth = maxDepth(root->left); //已经获取了左子树的深度
        int rightmaxDepth = maxDepth(root->right);//再获取右子树的深度

        return min(leftmaxDepth,rightmaxDepth)+1; //比较之后选大的,在加上当前结点+1        
    }
};

这里写图片描述

从结果中我们可以看出,当根节点的某一子树为NULL时,会保存为0.

代码


class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == NULL)
            return 0;

        //注意看题意,是从根节点到叶子节点的最短路径长度
        //如果不加两个if判断,当树只有两层,其中一侧还是NULL,那么比较判断min(0,1)会返回1

        //如果一开始从哪里进入递归,最终就会从哪里出来,然后返回,所以这里从根节点开始分了三种情况
        //1.根节点的左孩子为空
        //2.根节点的右孩子为空
        //3.根结点的左右孩子不为空
        if(root->left == NULL)
        {
            //当结点的左孩子为空,就去找右孩子的深度

            return 1+minDepth(root->right);
        }

        if(root->right == NULL)
        {
            return 1+minDepth(root->left);
        }

        int leftminDe = minDepth(root->left);
        int rightminDe = minDepth(root->right);

        return min(leftminDe,rightminDe)+1;
    }
};

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值