思路1:(DFS)
- 利用递归的结构,最小层次要么在左子树上产生,要么在右子树上产生
- 这种做法是比较慢的
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int left = minDepth(root->left);
int right = minDepth(root->right);
return (left == 0 || right == 0) ? left + right + 1 : min(left, right) + 1;
}
};
思路2:(BFS)
- 利用BFS的好处在于,可以不用读完整棵树
- 层次遍历,遍历到第一个叶子节点直接返回
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
int min_depth = 0;
if (!root) {
return 0;
}
queue<TreeNode*> q;
q.push(root);
int count_level = 0;
while (!q.empty()) {
int cur_level_size = q.size();
count_level++;
for (int i = 0; i < cur_level_size; ++i) {
TreeNode* cur_node = q.front();
q.pop();
if (!cur_node->left && !cur_node->right) {
min_depth = count_level;
return min_depth;
}
if (cur_node->left) q.push(cur_node->left);
if (cur_node->right) q.push(cur_node->right);
}
}
return min_depth;
}
};