mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 18:24:23 +08:00
1.8 KiB
1.8 KiB
题目地址
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
思路
C++代码
递归
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == NULL) return 0;
// 当一个左子树为空,右不为空,这时并不是最低点
if (node->left == NULL && node->right != NULL) {
return 1 + getDepth(node->right);
}
// 当一个右子树为空,左不为空,这时并不是最低点
if (node->left != NULL && node->right == NULL) {
return 1 + getDepth(node->left);
}
return 1 + min(getDepth(node->left), getDepth(node->right));
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
迭代法
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL) return 0;
int depth = 0;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
int size = que.size(); // 必须要这么写,要固定size大小
depth++;
int flag = 0;
for (int i = 0; i < size; i++) {
TreeNode* 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;
}
};
更多算法干货文章持续更新,可以微信搜索「代码随想录」第一时间围观,关注后,回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等,就可以获得我多年整理的学习资料。