LeetCode-111. 二叉树的最小深度

LeetCode-111. 二叉树的最小深度

难度:简单

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

class Solution {
public:

    // int fun(TreeNode* root ,int depth){
    //     if(!root->left && !root->right)return depth;
    //     int left = INT_MAX;
    //     int right = INT_MAX;
    //     if(root->left){
    //         left = fun(root->left,depth+1);
    //     }
    //     if(root->right){
    //         right = fun(root->right,depth+1);
    //     }
    //     return min(left,right);
                
    // }
    // int minDepth(TreeNode* root) {
    //     if(!root)return 0;
    //     return fun(root,1);
    // }

    int minDepth(TreeNode* root) {
        if(!root)return 0;
        queue<TreeNode*> q;
        q.push(root);
        int depth=0;
        int size;
        TreeNode *cur;
        while( !q.empty() ){
            size = q.size();
            depth++;
            while(size--){
                cur = q.front();
                q.pop();
                if(!cur->left && !cur->right)
                    return depth;
                if(cur->left)q.push(cur->left);
                if(cur->right)q.push(cur->right);
            }
            
        }
        return depth;
    }
};

执行结果:
通过

执行用时:
208 ms, 在所有 C++ 提交中击败了92.63%的用户
内存消耗:
141.1 MB, 在所有 C++ 提交中击败了91.42%的用户
通过测试用例:
52 / 52

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长不大的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值