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.
比较奇葩的设定,要是没有左子树,那么就要算右子树的最小高度。
- int minDepth(TreeNode *root) {
- if(root==NULL)
- return 0;
- int l=minDepth(root->left);
- int r=minDepth(root->right);
- if(l>0 && r>0)
- return min(l,r)+1;
- else
- return l+r+1;
- }
还有一种做法,比较直观:
int level;
int result;
int minDepth(TreeNode *root) {
level++;
if(root==NULL){
}
else if(root->left==NULL && root->right==NULL){
if(result==0)
result=level;
else
result=min(level,result);
}
else{
minDepth(root->left);
minDepth(root->right);
}
level--;
return result;
}