【LeetCode-111】Minimum Depth of Binary Tree(C++)
2016-09-17 12:27
543 查看
题目要求:给出一棵树,求出这棵树的最小深度,最小深度的意思是从该棵树的根节点到叶子节点的最短路径上的节点个数。
解题方法:相当于树的层序遍历,用两个队列来实现树中层次的划分,每遍历完一层,并且遍历的时候没有遇到叶子节点,就把深度值加一。只要遍历的过程中遇到了叶子节点,就返回深度值。
/**
* 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*> q1;
queue<TreeNode*> q2;
q1.push(root);
int depth=0;
while(!q1.empty()){
depth++;
TreeNode* p;
while(!q1.empty()){
p=q1.front();
q1.pop();
if(p->left==NULL&&p->right==NULL)
return depth;
if(p->left&&p->right){
q2.push(p->left);
q2.push(p->right);
}
else if(p->right){
q2.push(p->right);
}
else{
q2.push(p->left);
}
}
q1=q2;
while(!q2.empty()){
q2.pop();
}
}
return depth;
}
};
解题方法:相当于树的层序遍历,用两个队列来实现树中层次的划分,每遍历完一层,并且遍历的时候没有遇到叶子节点,就把深度值加一。只要遍历的过程中遇到了叶子节点,就返回深度值。
/**
* 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*> q1;
queue<TreeNode*> q2;
q1.push(root);
int depth=0;
while(!q1.empty()){
depth++;
TreeNode* p;
while(!q1.empty()){
p=q1.front();
q1.pop();
if(p->left==NULL&&p->right==NULL)
return depth;
if(p->left&&p->right){
q2.push(p->left);
q2.push(p->right);
}
else if(p->right){
q2.push(p->right);
}
else{
q2.push(p->left);
}
}
q1=q2;
while(!q2.empty()){
q2.pop();
}
}
return depth;
}
};
相关文章推荐
- 【leetcode c++】111 Minimum Depth of Binary Tree
- leetcode_c++:树: Minimum Depth of Binary Tree(111)
- leetcode 111 Minimum Depth of Binary Tree C++
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- leetcode_question_111 Minimum Depth of Binary Tree
- [C++]LeetCode: 30 Minimum Depth of Binary Tree
- leetcode || 111、Minimum Depth of Binary Tree
- Leetcode[111]-Minimum Depth of Binary Tree
- [leetcode 111] Minimum Depth of Binary Tree
- leetcode_111题——Minimum Depth of Binary Tree(二叉树,队列)
- leetcode[111]:Minimum Depth of Binary Tree
- LeetCode 111 Minimum Depth of Binary Tree
- [LeetCode 111] Minimum Depth of Binary Tree
- [LeetCode]111 Minimum Depth of Binary Tree
- leetcode 111 Minimum Depth of Binary Tree
- [leetcode 111] Minimum Depth of Binary Tree
- Leetcode_111_Minimum Depth of Binary Tree
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- Leetcode#111 Minimum Depth of Binary Tree
- leetCode #111 Minimum Depth of Binary Tree