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.
<pre name="code" class="cpp">class Solution
{
public:
int minDepth(TreeNode *root)
{
int nDepth, nLeftDep, nRightDep;
if (root == NULL)//如果根节点为空则返回0
return 0;
if (root->left == NULL&&root->right == NULL)//如果根节点的左右子树都是空则返回1
return 1;
nLeftDep = minDepth(root->left);
nRightDep = minDepth(root->right);
if (nLeftDep == 0)//如果左子树返回最大深度为0,则返回右子树最大深度
return nRightDep + 1;
if (nRightDep == 0)//如果右子树返回最大深度为0,则返回左子树最大深度
return nLeftDep + 1;
nDepth = nLeftDep < nRightDep ? nLeftDep : nRightDep;//比较左右子树返回的最大深度,取较小的
return nDepth + 1;
}
};