思路:
对于当前节点:
如果是叶子节点,则返回1;
如果其中一个子树没有,那么就要返回另一个子树的结果 + 1;
如果左右子树都存在,则返回两棵子树中的小结果 + 1;
code:
class Solution {
public:
int minDepth(TreeNode *root) {
if(root == NULL)return 0;
if(root->left == NULL && root->right == NULL)
return 1;
else if(root->left == NULL)
return minDepth(root->right) + 1;
else if(root->right == NULL)
return minDepth(root->left) + 1;
else
return min(minDepth(root->left),minDepth(root->right)) + 1;
}
};