15 Jun 2024C++ / Python / TypeScriptEasy

Minimum Depth of Binary Tree

Collected C++, Python, TypeScript solutions for minimum depth of binary tree. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Minimum Depth of Binary Tree. the solution files are available below.

solution files

  • C++ minimum-depth-of-binary-tree/synced-solution.cpp
  • Python minimum-depth-of-binary-tree/synced-solution.py
  • TypeScript minimum-depth-of-binary-tree/synced-solution.ts

Solution files

Pythonminimum-depth-of-binary-tree/synced-solution.py
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return class="syntax-number">0
        if not root.left:
            return class="syntax-number">1 + self.minDepth(root.right)
        if not root.right:
            return class="syntax-number">1 + self.minDepth(root.left)
        return class="syntax-number">1 + min(self.minDepth(root.left), self.minDepth(root.right))
C++minimum-depth-of-binary-tree/synced-solution.cpp
class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return class="syntax-number">0;
        if (!root->left) return class="syntax-number">1 + minDepth(root->right);
        if (!root->right) return class="syntax-number">1 + minDepth(root->left);
        return class="syntax-number">1 + min(minDepth(root->left), minDepth(root->right));
    }
};
TypeScriptminimum-depth-of-binary-tree/synced-solution.ts
function minDepth(root: TreeNode | null): number {
    if (!root) return class="syntax-number">0;
    if (!root.left) return class="syntax-number">1 + minDepth(root.right);
    if (!root.right) return class="syntax-number">1 + minDepth(root.left);
    return class="syntax-number">1 + Math.min(minDepth(root.left), minDepth(root.right));
}