题目描述:
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.
与求最大深度同理。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
else if(root->left==NULL&&root->right==NULL)
return 1;
else if(root->left!=NULL&&root->right==NULL)
return 1+minDepth(root->left);
else if(root->left==NULL&&root->right!=NULL)
return 1+minDepth(root->right);
else if(root->left!=NULL&&root->right!=NULL)
return 1+min(minDepth(root->left),minDepth(root->right));
}
};
本文介绍了一种求解二叉树最小深度的算法实现,通过递归方式找到从根节点到最近叶子节点的最短路径长度。文章提供了完整的C++代码示例,并详细解释了各种情况下的处理逻辑。

3129

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



