视频讲解:https://www.bilibili.com/video/BV1QD4y1B7e2/?vd_source=a935eaede74a204ec74fd041b917810c
文档讲解:https://programmercarl.com/0111.二叉树的最小深度.html
力扣题目:https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
这道题和求最大深度还有一点不一样,这道题的主要问题是找到最短的叶子节点,重要的是他需要是叶子节点,所以在递归过程中我们需要去判断是不是叶子节点,无非是两种情况1.左空又不空 2.右空左不空,当遇到这两种情况时,长度变为1+left/right,最后比较取最小值。
cpp
class Solution {
public:
int getDepth(TreeNode *node)
{
//判断终止条件
if(!node)
{
return 0;
}
//开始递归
int left=getDepth(node->left);
int right = getDepth(node->right);
//判断是不是叶子节点
if(node->left==NULL && node->right !=NULL)
{
return 1+right;
}
if(node->left!=NULL && node->right ==NULL)
{
return 1+left;
}
int result=1+min(right,left);
return result;
}
int minDepth(TreeNode* root) {
int result=getDepth(root);
return result;
}
};