刷题-Leetcode-111. 二叉树的最小深度(二叉树-属性)

111. 二叉树的最小深度

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

在这里插入图片描述在这里插入图片描述

题目分析

  1. 递归法
    注意最小深度求的是到叶子结点!!!,叶子结点没有孩子的结点。
    如果左子树为空 右子树不为空 最小深度=1+右子树的深度
    如果右子树为空 左子树不为空 最小深度=1+左子树的深度
    左右子树都为空 最小深度=1+min(左子树深度,右子树深度)
class Solution {
public:
    int getDept(TreeNode* root){
        if(root == nullptr) return 0;
        int leftDept = getDept(root->left);
        int rightDept = getDept(root->right);
        if(root->left == nullptr && root->right != nullptr){
            return 1 + rightDept;
        }else if(root->left != nullptr && root->right == nullptr){
            return 1 + leftDept;
        }else if(root->left == nullptr && root->right == nullptr){
            return 1;
        }
        //左右都不为空
        return 1 + min(leftDept, rightDept);
    }
    int minDepth(TreeNode* root) {
        return  getDept(root);
    }
};
  1. 迭代法
class Solution {
public:
    int minDepth(TreeNode* root) {
        int res = 0;
        queue<TreeNode*> que;
        if(root != nullptr) que.push(root);
        while(!que.empty()){
            int n = que.size();
            res++;
            while(n--){
                TreeNode* temp = que.front();
                que.pop();
                if(temp->left != nullptr) que.push(temp->left);
                if(temp->right != nullptr) que.push(temp->right);
                //在之前都没有左右孩子为空的时候 第一次到左右孩子为空 为最低点了
                if(temp->left == nullptr && temp->right == nullptr) return res;
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值