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));
}
}
如果我想为空节点返回0,为单节点返回1,为所有其他节点返回height-1会怎么样。 对于例如:对于具有7个元素{3,2,1,5,4,6,7}的BST,方法应该返回3而不是4 –
这有点不一致,因为它给出几个不同的树。但是,如果你真的想要,请查看更新。 – Henry
谢谢。我想确保我们必须使用另一个函数来实现这一点,这是递归不可能的。你认为我们可以使用相同的递归函数来实现吗? –