A C++ BFS solution, easy to understand


  • 0
    N

    The idea is sample, search every level to find the leaf node. It's similar to 102. Binary Tree Level Order Traversal
    and 104. Maximum Depth of Binary Tree.

        int minDepth(TreeNode* root) 
        {
            if (root == NULL)
                return 0;
            
            int deep = 0;
            queue<TreeNode*> q;
            q.push(root);
            while (!q.empty())
            {
                ++deep;
                int n = q.size();
                for(int i = 0; i < n; ++i)
                {
                    TreeNode* t = q.front();
                    q.pop();
                    
                    if (t->left == NULL && t->right == NULL)
                        return deep;
                    
                    if (t->left != NULL)
                        q.push(t->left);
                    if (t->right != NULL)
                        q.push(t->right);
                }
            }
        }
    

Log in to reply
 

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