gpt4 book ai didi

java - 使用递归求三叉树的高度?

转载 作者:行者123 更新时间:2023-12-01 10:44:45 26 4
gpt4 key购买 nike

我正在尝试找出如何为学校项目获取三元树的最大高度。对于二叉树,使用 Math.max() 很容易,但我在如何对三个 child 做同样的事情上遇到了困难。以下是我到目前为止所拥有的内容,但我还没有达到可以编译的程度,并且我不确定我的逻辑是否合理。这行得通吗?将左/右子比较放入临时变量中会更好吗?

private int getHeight(TernaryNode<T> node) {
int height = 0;

if (node != null) {
height = Math.max(getHeight(node.getLeftChild()), getHeight(node.getRightChild()));
height = 1 + Math.max(height, getHeight(node.getMidChild()));
}

return height;

最佳答案

是的,这会起作用。为了使其更具可读性,您可以编写 -

height = 1 + Math.max(
Math.max(
getHeight(node.getLeftChild()),
getHeight(node.getMidChild())
),
getHeight(node.getRightChild())
)

不需要辅助变量。

关于java - 使用递归求三叉树的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34254353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com