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),代码如下:
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; }
相关文章推荐
- Android异常处理之android.content.res.Resources$NotFoundException
- 新手站长该怎么入手网站推广
- Java实现水仙花数
- css整理03之盒模型
- Android笔记之BroadCast判断网络状况
- 新手站长心得体会大放送
- ubuntu12.04root密码设置
- 个人认为一些比较重要的题和答案
- 新手站长应该掌握的病毒式营销
- hashcode()和equals()方法
- BFS——NYOJ 21 三个水杯
- STC-ISP在Windows 7下使用方法
- Selenium WebDriver + Grid2 + RSpec之旅(五)---面向对象设计用例
- core--线程池
- 走进C++程序世界----类型转换运算符
- Android Dalvik虚拟机初识
- C#索引器
- Windows Server 2008安装Memcached笔记
- Linux软链接和硬链接
- 基础