LeetCode_111 二叉树的最小深度

1、题目:二叉树的最小深度

给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。

2、解题思路

方法一:递归

递归三步曲

1、确定递归函数的参数和返回值,参数为要传入的二叉树根节点,返回的是int类型的深度。

2、确定终止条件,终止条件也是遇到空节点返回0,表示当前节点的高度为0。

3、确定单层递归的逻辑,如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。

与最大深度基本一致,但是需要额外写出左右孩子不为空的逻辑。

方法二:迭代

 需要找到最小深度,只需要一层一层往下遍历,找到第一个叶子节点直接返回当前深度即可,所以在层序遍历的基础上改写代码。

LeetCode_102 二叉树的层序遍历_W__winter的博客-CSDN博客

3、代码

//递归
class Solution 
{
public:
    int getDepth(TreeNode* node) 
    {
        if (node == NULL) return 0;
        int leftDepth = getDepth(node->left);           // 左
        int rightDepth = getDepth(node->right);         // 右
                                                        // 中
        // 当一个左子树为空,右不为空,这时并不是最低点
        if (node->left == NULL && node->right != NULL) 
        { 
            return 1 + rightDepth;
        }   
        // 当一个右子树为空,左不为空,这时并不是最低点
        if (node->left != NULL && node->right == NULL) 
        { 
            return 1 + leftDepth;
        }
        int result = 1 + min(leftDepth, rightDepth);
        return result;
    }

    int minDepth(TreeNode* root) 
    {
        return getDepth(root);
    }
};
//迭代
class Solution 
{
public:

    int minDepth(TreeNode* root) 
    {
        if (root == NULL) return 0;
        int depth = 0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty())
        {
            int size = que.size();
            depth++; // 记录最小深度
            for (int i = 0; i < size; i++) 
            {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
                if (!node->left && !node->right) 
                { // 当左右孩子都为空的时候,说明是最低点的一层了,退出
                    return depth;
                }
            }
        }
        return depth;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值