0
点赞
收藏
分享

微信扫一扫

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

Greatiga 2022-01-05 阅读 137

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

举报

相关推荐

0 条评论