gpt4 book ai didi

java - 给定一个二叉树,其中每个节点都有一定的权重。您必须返回二叉树中的最大权重

转载 作者:行者123 更新时间:2023-11-30 21:21:32 25 4
gpt4 key购买 nike

Q> 给定一个二叉树,其中每个节点都有一定的权重。您必须返回二叉树中的最大权重。

Maxweight = 根节点的值 + 其左子树和右子树的值。

前-2 /\
-1 3输出 = 4

最佳答案

可以通过递归轻松解决,直到没有子节点为止。这是一个简单的例子:

weight = getWeight(rootNode)

getWeight(node)
{
if node != null
return node.weight + getWeight(node.leftChild) + getWeight(node.rightChild)
else
return 0
}

关于java - 给定一个二叉树,其中每个节点都有一定的权重。您必须返回二叉树中的最大权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25538422/

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