[LeetCode] 111. Minimum Depth of Binary Tree

来源:互联网 发布:联赢软件 编辑:程序博客网 时间:2024/05/24 02:12

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

// DFSclass Solution {public:    int minDepth(TreeNode* root) {        if (root == nullptr) return 0;        if (!root->right) return minDepth(root->left) + 1;  // only left branch        if (!root->left) return minDepth(root->right) + 1;  // only right branch        return min(minDepth(root->left), minDepth(root->right)) + 1;    // no or two    }};
// DFSclass Solution {public:    int minDepth(TreeNode* root) {        if (root == nullptr)            return 0;        if (root->left == nullptr && root->right == nullptr)            return 1;        int minDep = INT_MAX;        if (root->left)            minDep = min(minDep, minDepth(root->left) + 1);        if (root->right)            minDep = min(minDep, minDepth(root->right) + 1);        return minDep;    }};
// DFSclass Solution {public:    int minDepth(TreeNode* root) {        if (root == nullptr) return 0;        int MinDepth = INT_MAX;        minDepth(root, 1, MinDepth);        return MinDepth;    }private:    void minDepth(TreeNode *root, int level, int& MinDepth) {        if (root->left == nullptr && root->right == nullptr)            MinDepth = min(level, MinDepth);        if (root->left)            minDepth(root->left, level + 1, MinDepth);        if (root->right)            minDepth(root->right, level + 1, MinDepth);    }};
// BFSclass Solution {public:    int minDepth(TreeNode* root) {        if (root == nullptr) return 0;        int level = 1;        queue<TreeNode *> q;        q.push(root);        q.push(nullptr);        while (!q.empty()) {            TreeNode *ptn = q.front();            q.pop();            if (ptn == nullptr) {                level++;                if (!q.empty())                    q.push(nullptr);                continue;            }            if (ptn->left == nullptr && ptn->right == nullptr)                break;            else {                if (ptn->left) q.push(ptn->left);                if (ptn->right) q.push(ptn->right);            }        }        return level;    }};
原创粉丝点击