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.
关键点:1)必须注意考虑左孩子或者右孩子为空的情况。
/**
* Definition for binary tree* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isleaf(TreeNode *node)
{
if(NULL == node)
return false;
if((NULL == node->left) && (NULL == node->right))
return true;
else
return false;
}
int minDepth(TreeNode *root) {
if(NULL == root)
return 0;
if(isleaf(root))
return 1;
if(NULL == root->left)
return 1 + minDepth(root->right);
if(NULL == root->right)
return 1 + minDepth(root->left);
if((1+minDepth(root->left)) <= (1 + minDepth(root->right)))
return 1 + minDepth(root->left);
else
return 1 + minDepth(root->right);
}
};