题目:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
思路:
对于每个node的判断,总共分三种情况:
- 无左子树,无右子树。此节点为叶子节点,返回1。
- 有左子树,无右子树。返回左子树高度+1。
- 无左子树,有右子树。返回右子树高度+1。
- 有左子树,有右子树。返回min(左子树高度,右子树高度)+1。
代码实现:
/**
* 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 f(TreeNode* root){
if (root == nullptr){
return 0;
}
int left_depth = f(root->left);
int right_depth = f(root->right);
if (left_depth == 0 && right_depth == 0){
return 1;
}else if (left_depth == 0){
return right_depth + 1;
}else if (right_depth == 0){
return left_depth + 1;
}
return min(left_depth, right_depth)+1;
}
int minDepth(TreeNode* root) {
return f(root);
}
};
discuss:
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
return (!left || !right) ? left + right + 1 : min(left, right) + 1;
}
};
本文详细解析了寻找二叉树最小深度的算法,通过递归方式判断节点状态,包括叶子节点、单边子树及双边子树情况,最终实现高效求解最短路径到叶节点的节点数。
452

被折叠的 条评论
为什么被折叠?



