标签:
思路:用队列实现广度优先搜索即可,将每一层的节点放入队列,然后弹出时将下一层节点放入,遇到叶子节点时即返回当前的高度
class Solution {
public:
int minDepth(TreeNode *root) {
if (!root)
return 0;
int length = 0;
queue<TreeNode*> qnode;
qnode.push(root);
TreeNode* tmpNode;
while (!qnode.empty())
{
length++;
int qsize = qnode.size();
for (int i = 0; i < qsize; i++)
{
tmpNode = qnode.front();
if (!tmpNode->left && !tmpNode->right)
return length;
if (tmpNode->left)
qnode.push(tmpNode -> left);
if (tmpNode->right)
qnode.push(tmpNode->right);
qnode.pop();
}
}
return length;
}
};
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/02d3a3aefc496afa188ab2abcdab7354.html