PU Minimum Depth of Binary Tree

Jan 01, 1970

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

C Solution 1:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int minDepth(struct TreeNode* root) {
    if (!root) return 0;
    if (!root->left && !root->right) {
        return 1;
    }
    int left = root->left ? minDepth(root->left) : INT_MAX;
    int right = root->right ? minDepth(root->right) : INT_MAX;
    return (left < right ? left : right) + 1;
}

C Solution 2:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int minDepth(struct TreeNode* root) {
    if (!root) return 0;
    int left = minDepth(root->left);
    int right = minDepth(root->right);
    if (!left && !right) return 1;
    if (left && right) return (left < right ? left : right) + 1;
    return left + right + 1;
}

Summary:

  • Try to avoid define another function.

LeetCode: 111. Minimum Depth of Binary Tree