Minimum Depth of Binary Tree
来源:互联网 发布:一个网络协议主要由 编辑:程序博客网 时间:2024/05/22 21:39
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> Q1,Q2;
// vector<int>level;
// vector<vector<int>>result;
TreeNode* node;
int i=1;
if(!root) return 0;
Q1.push(root);
while(!Q1.empty())
{
while(!Q1.empty())
{
node=Q1.front();
Q1.pop();
if(node->left==NULL&&node->right==NULL)
return i;
if(node->left!=NULL)
Q2.push(node->left);
if(node->right!=NULL)
Q2.push(node->right);
}
swap(Q2,Q1);
i++;
}
}
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> Q1,Q2;
// vector<int>level;
// vector<vector<int>>result;
TreeNode* node;
int i=1;
if(!root) return 0;
Q1.push(root);
while(!Q1.empty())
{
while(!Q1.empty())
{
node=Q1.front();
Q1.pop();
if(node->left==NULL&&node->right==NULL)
return i;
if(node->left!=NULL)
Q2.push(node->left);
if(node->right!=NULL)
Q2.push(node->right);
}
swap(Q2,Q1);
i++;
}
}
};
主要是用层序遍历的思路,碰到一个左右节点为空的即可返回。 两层while循环。
0 0
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- [数学]Sum of f(x) 约数之和问题
- AppDelegate生命周期详解
- 面试常考的atoi函数
- jsp 有哪些内置对象?作用分别是什么?
- 决策树的Python代码分析(一)
- Minimum Depth of Binary Tree
- Spring Bean的5种作用域
- MVVM
- hibernate 懒加载异常
- COM学习笔记2_COM接口vbtl内存布局
- libgdx html 跨平台的坑
- Trie树
- jQuery图片裁剪插件
- 为什么C/C++的参数入栈顺序是从右向左?