104:
class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); return (left > right ? left : right) + 1; } };
111:
class Solution { public: int minDepth(TreeNode* root) { if(root == NULL) return 0; int left = minDepth(root->left); int right = minDepth(root->right); if(left == 0) return right + 1; else if(right == 0) return left + 1; else return left < right ? left + 1 : right + 1; } };
最小的深度这个题与最大的深度这个题稍稍有点不同,因为最小深度的计算必须从叶子节点开始,没有叶子节点不能计算,所以1,2这种情况只能返回2,不能返回1。做个判断即可。