2017-03-10 99 views
0

我写了一个方法来返回二叉搜索树的高度。我想从递归方法返回height - 1。我通过添加额外的if条件来完成此操作。递归:如何从递归函数返回值-1

有没有更好的方法来从递归函数中返回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)); 
    } 
} 

回答

3

在你的基地的情况下返回-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)); 
} 

更新以符合在评论中提及的要求:“如果我想为单节点空节点,1返回0什么如果所有其他的高度为1“。

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

如果我想为空节点返回0,为单节点返回1,为所有其他节点返回height-1会怎么样。 对于例如:对于具有7个元素{3,2,1,5,4,6,7}的BST,方法应该返回3而不是4 –

+0

这有点不一致,因为它给出几个不同的树。但是,如果你真的想要,请查看更新。 – Henry

+0

谢谢。我想确保我们必须使用另一个函数来实现这一点,这是递归不可能的。你认为我们可以使用相同的递归函数来实现吗? –