Minimum Depth of Binary Tree

Solution Code
Definition for a binary tree node.class TreeNode:def init(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightclass Solution:def minDepth(self, root: Optional[TreeNode]) -> int:if not root:return 0# If left subtree is empty, recurse on the right subtree
    if not root.left:
        return self.minDepth(root.right) + 1
    
    # If right subtree is empty, recurse on the left subtree
    if not root.right:
        return self.minDepth(root.left) + 1
    
    # If both subtrees exist, take the minimum of the two depths
    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1

Time Complexity

O(N)

Space Complexity

O(N)