How to Find Minimum Depth of Binary Tree Using Iterative Approach (BFS iteration)

Find Minimum Depth of Binary Tree. The number of nodes along the shortest route from the root node down to the closest leaf node is the minimal depth.

// using BFS
// in this method, we just have to count levels of tree that will become its height.

class Solution {
public:
    int minDepth(TreeNode* root) {
        
        if(root == NULL)
            return 0;
        
        int level = 0;
        queue <TreeNode*> q;
        q.push(root);
        
        while(!q.empty()){
            int currLength = q.size();
            level++;
            
            //Iterate till the current length of Queue
            for(int i=0; i<currLength; i++){
                TreeNode* curr = q.front();
                q.pop();
                
                if(curr -> left)
                    q.push(curr -> left);
                if(curr -> right)
                    q.push(curr -> right);
                
                // If Both left and right nodes are null, means we reached minimum height
                // at that time time level i.e. height
                if(curr -> left == NULL && curr -> right == NULL){
                    return level;
                }
            }
        }
        return level;
    }
};

This Article Credits goes to Harcharan Preet Singh.

Advertisements
Skip advert

Leave a Reply

Your email address will not be published.