题目描述
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.
翻译(使用Google翻译):给定二叉树,找到它的最小深度。最小深度是沿从根节点到最近的叶节点的最短路径上的节点数。
//使用一个队列遍历,如果本次遍历时,有一个结点的左右子树都为NULL,说明
//它是一个叶子结点,因为是深度优先遍历,所以这个结点到跟的路径长度就是最
//小深度。
class Solution {
public:
int run(TreeNode *root) {
queue<TreeNode*> q;
if(root==NULL)return 0;
int depth=1;
q.push(root);
while(q.empty()!=true)
{
int mark_num=q.size();
while(mark_num)
{
auto ptr=q.front();
q.pop();
if(ptr->left==NULL&&ptr->right==NULL)return depth;
else{
if(ptr->left!=NULL)q.push(ptr->left);
if(ptr->right!=NULL)q.push(ptr->right);
}
mark_num--;
}
depth++;
}
return depth;
}
};