leetcode

Minimum Depth of Binary Tree

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.

we need to add check for node which doesn't have left or right child, because if we just do min(root,left, root.right), it will always return 0, which is wrong, the height is calculated only at the leaf node.

public int minDepth(TreeNode root) {
        if (root==null) {
            return 0;
        }

        //need to consider if left child is null or right child is null
        //   1 
        // 2
        if (root.left==null) {
            return 1+minDepth(root.right);
        } else if (root.right==null) {
            return 1+minDepth(root.left);
        } else {
            return 1+Math.min(minDepth(root.left), minDepth(root.right));
        }        
    }