繁体   English   中英

递归:如何从递归函数返回value-1

[英]Recursion : How do I return value-1 from recursive function

我编写了一种方法来返回二进制搜索树的高度。

现在,我尝试从递归方法返回height - 1 我通过添加额外这样做if条件。

是否有更好的方法从递归函数返回value - 1

static int height(Node root) {
    if (root == null) {       
        return 0;
    }

    if (root.left == null && root.right==null) {      
        return 1;            
    } else
        // I want to return height - 1.
        // For example if max height is 10, I wanted to return 9.
        return (1 + Math.max(height(root.left), height(root.right));   
    }
}

在您的基本情况下,分别返回-1和0:

static int height(Node root) {
    if(root == null)       
        return -1;
    if(root.left == null && root.right==null)      
        return 0;            
    else
        return 1+ Math.max(height(root.left),
                   height(root.right));   
}

更新以符合注释中提到的要求:“如果我想为空节点返回0,为单节点返回1,而对于所有其他节点返回height-1,该怎么办?”

static int funny_height(Node root) {
    int h = height(node);
    return h <= 0 ? h + 1 : h;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM