层次遍历的过程中,用depth记录当前层次的深度,只要发现结点的左右指针均为空,立即返回此时的depth;
代码:
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL) return 0;
queue<TreeNode *> q;
q.push(root);
int depth = 0, len = 0;
while (!q.empty()) {
depth++;
len = q.size();
while (len--) {
TreeNode *temp = q.front();
q.pop();
if (!temp->left && !temp->right) return depth;
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
}
}
}
};