1、题目描述
2、分析
求树的最小深度,递归求出左右子树,返回其中小的那个。需要注意的是这里的叶子节点指的是两个子节点都为空的节点,如果只是其中一个子节点为空那么需要返回的是另一个的高。
3、代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return 1;
int h1=minDepth(root->left);
int h2=minDepth(root->right);
if(root->left==NULL||root->right==NULL){
return h1+h2+1;
}
return min(h1,h2)+1;
}
};
4、相关知识点
树的高度的相关求解。