方法一:(深度优先搜索,记得单个结点深度为1,注意边界情况。)
class Solution {
public:
int minDepth(TreeNode *root) {
if(root==0)
return 0;
if(root->left==NULL&&root->right==NULL)
return 1;
int l=0x3f3f3f3f,r=0x3f3f3f3f;
if(root->left!=NULL)
l=1+minDepth(root->left);
if(root->right!=NULL)
r=1+minDepth(root->right);
return min(l,r);
}
};111 Minimum Depth of Binary Tree
最新推荐文章于 2019-04-03 10:24:47 发布
本文介绍了一种使用深度优先搜索(DFS)算法来计算二叉树最小深度的方法。当根节点为空返回0;若左右子节点都为空则当前节点深度为1;通过递归左右子树获取最小深度。
1114

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



