Minimum Depth of Binary Tree
2015-10-20 19:51
176 查看
题目: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,这个加1都是由当前层向下一层递进的时候加1的。如果左右节点存在,则存入堆栈。不存在不进行任何操作。
重要的是:最小高度是指从根节点到最近的叶子节点的最小高度,是指没有的叶子节点。也就是说,只要没有孩子了,就返回。
代码:
/*** Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//https://leetcode.com/problems/minimum-depth-of-binary-tree/
class Solution1 {
public:
int minDepth(TreeNode* root) {
if(root==NULL){
return 0;
}
if(root->left==NULL&&root->right==NULL){
return 1;
}
int left=INT_MAX;
if(root->left){
left=minDepth(root->left)+1;
}
int right=INT_MAX;
if(root->right){
right=minDepth(root->right)+1;
}
return min(left,right);
//如果直接写 return min(minDepth(root->left)+1,minDepth(root->right)+1)这句的话
//实际上忽略了根节点,一定是从根节点到叶子的最短距离
}
};
class Solution2 {
public:
int minDepth(TreeNode* root) {
return BFS(root);
}
int BFS(TreeNode * root){
if(root==NULL){
return 0;
}
queue<pair<TreeNode*,int> >q;
q.push(make_pair(root,1));
while(!q.empty()){
TreeNode *curNode=q.front().first;
int curStep=q.front().second;
q.pop();//这一层结束
if(curNode->left==NULL&&curNode->right==NULL){
return curStep;
//本题的意思就是只要有一层第一个出现空节点就是最小值
}
if(curNode->left!=NULL){
q.push(make_pair(curNode->left,curStep+1));
}
if(curNode->right!=NULL){
q.push(make_pair(curNode->right,curStep+1));
}
//本题的巧妙在于我每次都存入一层的节点,当然是没有空的情况下
//当然题目一开始就判断了,如果下一个节点的左右孩子是空的话,直接返回
}
}
};
相关文章推荐
- Android第三方开源ImageLoader的使用(一)
- 设计模式之一 设计模式概述
- 爬爬爬之路:C语言(九) 结构体指针与预编译指令
- Java 8.1
- c++数组访问越界的问题
- jquery的ajax
- ios开发之c语言基础-结构体
- android 随机云标签(圆形)
- 内存映射文件 进程间通讯
- DELPHI 让子窗体显示在任务栏上
- HBase深入学习笔记
- 参加某项目例会小记-2015-10-20
- 如何访问到静态的文件,如jpg,js,css?
- MySQL数据库高并发优化配置
- Android studio通过JNI调用动态链接库SO
- 图形的几何变换(平移,比例,定点比例)
- 将 nginx 安装成 windows 的方法
- 【软剑攻城队】用户需求分析文档发布!
- 洛谷1281 书的复制
- 让代码帮助我们研发--代码半自动化