The number of nodes in the tree is in the range [0, 105].
-1000 <= Node.val <= 1000
Solutions
Solution 1: Recursion
The termination condition for recursion is when the current node is null, at which point return $0$. If one of the left or right subtrees of the current node is null, return the minimum depth of the non-null subtree plus $1$. If neither the left nor right subtree of the current node is null, return the smaller value of the minimum depths of the left and right subtrees plus $1$.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 9101112131415
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defminDepth(self,root:Optional[TreeNode])->int:ifrootisNone:return0ifroot.leftisNone:return1+self.minDepth(root.right)ifroot.rightisNone:return1+self.minDepth(root.left)return1+min(self.minDepth(root.left),self.minDepth(root.right))
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcminDepth(root*TreeNode)int{ifroot==nil{return0}ifroot.Left==nil{return1+minDepth(root.Right)}ifroot.Right==nil{return1+minDepth(root.Left)}return1+min(minDepth(root.Left),minDepth(root.Right))}