111.Minimum Depth of Binary Tree

Posted smallredness

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了111.Minimum Depth of Binary Tree相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        if (!root->left) return 1 + minDepth(root->right);
        if (!root->right) return 1 + minDepth(root->left);
        return 1 + min(minDepth(root->left), minDepth(root->right));
    }
};
class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            ++res;
            for (int i = q.size(); i > 0; --i) {
                auto t = q.front(); q.pop();
                if (!t->left && !t->right) return res;
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
        }
        return -1;
    }
};

以上是关于111.Minimum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章