题目链接
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
if (!root->left) {
return 1 + minDepth(root->right);
}
if (!root->right) {
return 1 + minDepth(root->left);
}
return 1 + min(minDepth(root->left), minDepth(root->right));
}
};
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
queue<TreeNode*> que;
que.push(root);
int depth = 0;
while (!que.empty()) {
int size = que.size();
TreeNode* node;
depth++;
int flag = 0;
for (int i = 0; i < size; i++) {
node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
if (!node->left && !node->right) {
flag = 1;
break;
}
}
if (flag == 1)
break;
}
return depth;
}
};
