您的位置:首页 > 其它

Minimum Depth of Binary Tree

2013-11-16 17:34 337 查看
题目描述:


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.


一看到这个题目的时候,想一层一层的数一下,仔细一想貌似不太靠谱,要么改结点结构,要么把结点在第几层存到另外的数据结构中。再一想其实很简单,就像一个递归定义:


当前树的minimum depth等于:
1.左右子树都不为空时,为子树中较小的minimum depth+1;
2.有一个子树为空时,为非空子树的minimum depth+1;
3.都为空时,为1。


这样就可以解决了,时间复杂度为O(n),代码如下:

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

int rmin=minDepth(root->right);
int lmin=minDepth(root->left);
if(root->left==NULL)
return rmin+1;
if(root->right==NULL)
return lmin+1;
int c = min(lmin,rmin)+1;
return c;
}
int min(int a,int b){
return a<b?a:b;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: