C++ 6ms loop BFS solution


  • 0
    C
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int minDepth(TreeNode* root) {
            if (root == NULL)
                return 0;
            int depth = 1;
            queue<TreeNode *> q, cage;
            q.push(root);
            while (true) {
                while (!q.empty()) {
                    TreeNode * node = q.front();
                    q.pop();
                    if (node->left == NULL && node->right == NULL)
                        return depth;
                    if (node->left) cage.push(node->left);
                    if (node->right)    cage.push(node->right);
                }
                ++depth;
                q = cage;
                cage = queue<TreeNode *>();
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.