思路:一开始以为这个题和104题的“
Maximum Depth of Binary Tree”是一样,后来发现不是那么回事,存在理解上的错误。只有左右孩子都为空的节点才算是叶节点,所以当根节点只有左孩子而没有右孩子的时候,它的最小深度应该是2,而不是1。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL && root->right==NULL) 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;
}
};
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL && root->right==NULL) 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;
}
};