Minimum depth LeetCode (111) binary tree

Minimum depth (111) of the binary tree

Description:

Given a binary tree, to find out the minimum depth.

Minimum depth is the number of nodes in the shortest path from the root node to leaf nodes nearest.

Description:

Leaf node is a node does not have child nodes.

Example:

给定二叉树 [3,9,20,null,null,15,7],
 3
/ \
9  20
 /  \
15   7
返回它的最小深度  2.

Ideas:

Actually very simple, the general idea is to drink seek maximum depth opposite. But note that the description 叶子节点是指没有子节点的节点。 should be noted that, at the time of writing code to eliminate such a scenario. Or will be in [1, 2]the fall.

Code:

int minDepth(struct TreeNode* root){
    if(root == NULL)return 0;
    if(root -> left == NULL && root -> right != NULL){
        return 1 + minDepth(root -> right);
    }
    if(root -> left != NULL && root -> right == NULL){
        return 1 + minDepth(root -> left);
    }

    int left = minDepth(root -> left);
    int right = minDepth(root -> right);
    return left > right ? right + 1 : left + 1;
}
Released six original articles · won praise 1 · views 47

Guess you like

Origin blog.csdn.net/LordTech/article/details/104283445