Skip to content

Latest commit

 

History

History
102 lines (84 loc) · 2.37 KB

_111. Minimum Depth of Binary Tree.md

File metadata and controls

102 lines (84 loc) · 2.37 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 07, 2024

Last updated : July 04, 2024


Related Topics : Tree, Depth-First Search, Breadth-First Search, Binary Tree

Acceptance Rate : 49.75 %


Solutions

C

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

int min(int a, int b) {
    return (a < b) ? a : b;
}

int minDepthHelper(struct TreeNode* current) {
    if (!current->left && !current->right) 
        return 1;
    if (!current->left)
        return 1 + minDepthHelper(current->right);
    if (!current->right)
        return 1 + minDepthHelper(current->left);

    return 1 + min(minDepthHelper(current->left), minDepthHelper(current->right));
}
int minDepth(struct TreeNode* root) {
    if (!root)
        return 0;
    return minDepthHelper(root);
}

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return minDepth(root, 1);
    }
    private int minDepth(TreeNode curr, int depth) {
        if (curr.left == null && curr.right == null) {
            return depth;
        }

        depth++;
        if (curr.left != null && curr.right != null) {
            return Integer.min(minDepth(curr.left, depth), minDepth(curr.right, depth));
        }

        if (curr.left != null) {
            return minDepth(curr.left, depth);
        }
        return minDepth(curr.right, depth);
    }
}