[LeetCode] Minimum Depth of Binary Tree - BFS

来源:互联网 发布:网络三大奇书四大神书 编辑:程序博客网 时间:2024/05/01 12:50
/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int minDepth(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if (!root) return 0;                queue<TreeNode *> q;        q.push(root);        q.push(NULL);                int ret = 1;                while (!q.empty()) {            TreeNode *node = q.front();            q.pop();                        if (!node) {                ret++;                q.push(NULL);            } else {                if (!node->left && !node->right) break;                if (node->left) q.push(node->left);                if (node->right) q.push(node->right);            }        }                return ret;    }};


Small Case: 8ms

Large Case: 92ms


Time: O(n)

Space: O(n)


BFS version.

原创粉丝点击