Iterative cpp solution using a queue


  • 0
    C
    class Solution {
    public:
        // using a queue to find the shortest path
        
        int minDepth(TreeNode* root) 
        {
            if(!root) return 0;
            
            queue<TreeNode*> q;
            q.push(root);
            
            int min_h = 0;
            
            while( !q.empty() )
            {
                int level_cnt = q.size();
                min_h++;
                
                while(level_cnt-- > 0)
                {
                    TreeNode *n = q.front();
                    q.pop();
                    
                    if(!n->left && !n->right)
                        return min_h;
                    
                    if(n->left) q.push(n->left);
                    if(n->right) q.push(n->right);
                }
            }
            
            return min_h;
        }
    };

Log in to reply
 

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