In this Leetcode Minimum Depth of Binary Tree problem solution we have 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.

Leetcode Minimum Depth of Binary Tree problem solution


Problem solution in Python.

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if (root == None):
            return 0
        self.height = 1<<30
        def depth(node,height):
            if (node):
                if (node.left == None) and (node.right == None):
                    self.height = min(self.height,height)
                if (node.left):
                    depth(node.left,height+1)
                if (node.right):
                    depth(node.right,height + 1)
        depth(root,1)
        return self.height



Problem solution in Java.

public int minDepth(TreeNode root) {
	if (root == null) return 0;
	if (root.left == null) return 1 + minDepth(root.right);
	if (root.right == null) return 1 + minDepth(root.left);
	return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}


Problem solution in C++.

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        int left_depth  = minDepth(root->left);
        int right_depth = minDepth(root->right);
        if(left_depth == 0 || right_depth == 0)
            return left_depth + right_depth + 1;
        return min(left_depth, right_depth)+1;
    }

};


Problem solution in C.

int minDepth(struct TreeNode* root){
   if(root==NULL) return 0;
   struct TreeNode* arr[100000];
    int head=1, tail=-1;
    arr[0] = root;
    root->val=1;
    while (head!=tail){
		tail++;
        if(arr[tail]->left ==NULL && arr[tail]->right ==NULL) break;
        if(arr[tail]->left !=NULL){
            arr[head++] = arr[tail]->left;
            arr[tail]->left->val = arr[tail]->val+1;
        }
        if(arr[tail]->right !=NULL){
             arr[head++] = arr[tail]->right;
            arr[tail]->right->val = arr[tail]->val+1;
        }
    }
    return arr[tail]->val;
    
}