LeetCode Solutions

111. Minimum Depth of Binary Tree

Time: $O(n)$

Space: $O(h)$

			

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

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

class Solution:
  def minDepth(self, root: Optional[TreeNode]) -> int:
    if not root:
      return 0
    if not root.left:
      return self.minDepth(root.right) + 1
    if not root.right:
      return self.minDepth(root.left) + 1
    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1