您的位置:首页 > 编程语言 > C语言/C++

【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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息