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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode *root) {
if(root==NULL)
{
return 0;
}
TreeNode* pTemp=root;
if(pTemp->left==NULL)
{
return minDepth(pTemp->right)+1;
}
if(pTemp->right==NULL)
{
return minDepth(pTemp->left)+1;
}
int nLeft=minDepth(pTemp->left);
int nRight=minDepth(pTemp->right);
return nLeft<nRight? (nLeft+1):(nRight+1);
}
};