【问题标题】:Recursion : How do I return value-1 from recursive function递归:如何从递归函数返回 value-1
【发布时间】:2017-03-10 16:16:03
【问题描述】:

我写了一个方法来返回二叉搜索树的高度。

现在我正在尝试从递归方法返回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));   
    }
}

【问题讨论】:

    标签: java recursion binary-search-tree


    【解决方案1】:

    在您的基本情况下分别返回 -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;
    }
    

    【讨论】:

    • 如果我想为空节点返回 0,为单个节点返回 1,为所有其他节点返回 height-1。例如:对于具有 7 个元素 {3,2,1,5,4,6,7} 的 BST,方法应返回 3 而不是 4
    • 这有点不一致,因为它为几种不同的树给出了 1。但如果你真的想要,请查看更新。
    • 谢谢。我想确保我们必须使用另一个函数来实现这一点,而递归是不可能的。你认为我们可以使用相同的递归函数来实现这一点吗?
    • 我认为没有一种简单易懂的方法可以仅在一个递归函数中完成。这可能是该要求有些缺陷的另一个暗示。
    • 我只是想知道这是否可能。我没有任何要求,这是出于好奇。感谢您的投入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2012-09-19
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多