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。做个判断即可。

相关文章:

  • 2022-12-23
  • 2021-05-02
  • 2021-12-10
  • 2021-09-07
  • 2021-06-05
  • 2021-07-22
  • 2021-08-07
猜你喜欢
  • 2021-09-23
  • 2021-12-21
  • 2021-04-17
  • 2021-08-21
  • 2021-11-02
  • 2021-06-09
  • 2022-12-23
相关资源
相似解决方案