最大深度:

   int maxDepth(TreeNode *root)
    {
        if(root == NULL)
            return 0;
        if(root->left == NULL && root->right == NULL)
            return 1;
        int left = maxDepth(root->left) + 1;
        int right = maxDepth(root->right) + 1;
        return left>right ? left : right;    //返回二者之中较大数
    }

最小深度:

    int minDepth(TreeNode * root)
    {
        if(root == NULL)
            return 0;
        if(root->left == NULL && root->right == NULL)
            return 1;
        int left = minDepth(root->left) + 1;
        int right = minDepth(root->right) + 1;
        if(left == 1)          //等于1说明没有左子树有右子树,为避免干扰结果,另其为一个最大数
            left = INT_MAX;
        if(right == 1)         //等于1说明没有右子树有左子树,为避免干扰结果,另其为一个最大数
            right = INT_MAX;
        return left > right ? right : left;    //返回二者之中较小数
    }

 

相关文章:

  • 2021-10-28
  • 2022-12-23
  • 2020-06-15
  • 2021-11-01
  • 2021-05-03
猜你喜欢
  • 2021-11-04
  • 2021-06-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-21
  • 2022-02-17
相关资源
相似解决方案