Minimum Depth of Binary Tree @LeetCode

PROBLEM :

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Using Queue )
--------------------------------------------------------------------------------

 /**
 * 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 ;
         
        queue<TreeNode*> que ;
        que.push(root) ;
        int depth=0 ;
     
        while(!que.empty()){
            int n=que.size() ;
            depth++ ;
         
            while(n--){
                TreeNode* node=que.front() ;
                que.pop() ;
             
                if(node->left==NULL&&node->right==NULL)
                    return depth ;
             
                if(node->left)
                    que.push(node->left) ;
                if(node->right)
                    que.push(node->right) ;
            }
        }
    }
};


--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Better Solution )
--------------------------------------------------------------------------------

/**
 * 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 l=minDepth(root->left) ;
        int r=minDepth(root->right) ;
     
        return (l==0||r==0)?l+r+1:(l<r?l+1:r+1) ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )