1.题目:
给定一个二叉树,找出其最小深度。最
小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
2.示例:
3.思路:
利用递归实现,当前节点的左右节点都为NULL时判断当前节点为子节点。
4.代码:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL&&root->right==0) return 1;
if(root->left==NULL) return minDepth(root->right)+1;
if(root->right==NULL) return minDepth(root->left)+1;
return min(minDepth(root->left),minDepth(root->right))+1;
}