ADVERTISEMENTS

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.

ADVERTISEMENTS
// 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

MOST SHARED

LEAVE A REPLY

Please enter your comment!
Please enter your name here

ADVERTISEMENTS

Amazon Kindle Scribe vs Kindle Paperwhite (updated 2022)

Amazon Kindle Scribe vs Kindle Paperwhite (2022): What else is new with the next-generation e-reader? Amazon is expanding the Kindle's capabilities beyond reading. The Kindle...
ADVERTISEMENTS

Most Popular