leetcode刷题,总结,记录,备忘111
2016-04-09 21:01
369 查看
leetcode111Minimum Depth of Binary Tree
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.
Subscribe to see which companies asked this question
通过队列保存树的每个节点,使用一个变量记录当前层的节点个数,每遍历完一层深度加1,当遇到叶节点的时候返回深度即可,比较简单的题目。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
queue<TreeNode*> qt;
qt.push(root);
int deep = 1;
int count = 1;
while (!qt.empty())
{
TreeNode * t = qt.front();
qt.pop();
count--;
if (t->left == NULL && t->right == NULL)
{
return deep;
}
if (t->left)
{
qt.push(t->left);
}
if (t->right)
{
qt.push(t->right);
}
if (count == 0)
{
count = qt.size();
deep++;
}
}
return deep;
}
};
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.
Subscribe to see which companies asked this question
通过队列保存树的每个节点,使用一个变量记录当前层的节点个数,每遍历完一层深度加1,当遇到叶节点的时候返回深度即可,比较简单的题目。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
queue<TreeNode*> qt;
qt.push(root);
int deep = 1;
int count = 1;
while (!qt.empty())
{
TreeNode * t = qt.front();
qt.pop();
count--;
if (t->left == NULL && t->right == NULL)
{
return deep;
}
if (t->left)
{
qt.push(t->left);
}
if (t->right)
{
qt.push(t->right);
}
if (count == 0)
{
count = qt.size();
deep++;
}
}
return deep;
}
};
相关文章推荐
- LeetCode118—Pascal's Triangle
- 飞机加油问题
- bzoj 1910: [Ctsc2002] Award 颁奖典礼 动态规划
- sqlite数据库简介
- iOS依赖管理工具--CocoaPods
- 独立项目 - 2 - Mac配置retrolambda
- 算法:动态规划(新手勿喷)
- KMP算法
- Oracle配置文件详解 listener.ora,sqlnet.ora,tnames.ora
- Hbase 学习笔记5----hbase region, store, storefile和列簇的关系
- MS WORD 表格自己主动调整列宽,自己主动变美丽,依据内容自己主动调整
- html5学习系列之klm类标签
- LeetCode Best Time to Buy and Sell Stock II
- 最大子数组(C语言)
- 使用Princeton(普利斯顿大学)的Java标准库的方法
- 阿里音乐流行趋势预测大赛一起做-(2)weka初识
- request请求路径
- jrMz and angles
- 视频连接
- 【九度OJ】题目1202:排序