[LeetCode] Minimum Depth of Binary Tree

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.

我记得有一题是叫算Max depth 的,如出一辙。思路就是拿到一颗树,分别算出他左右子树的min depth,然后返回其中最小的那个+1就行了。

但是要注意的是和max depth有区别的地方在于,要判断左右子树存不存在先,如果不存在就忽略了。

int minDepth(TreeNode *root) {
    if (!root) return 0;
    if (!root->left && !root->right) return 1;
    
    int leftMin = INT_MAX;
    int rightMin = INT_MAX;
    
    if (root->left)
        leftMin = minDepth(root->left);
    if (root->right)
        rightMin = minDepth(root->right);
    
    return leftMin < rightMin ? leftMin+1 : rightMin+1;
}
原文地址:https://www.cnblogs.com/agentgamer/p/4094179.html