【问题标题】:given a binary tree where each node has some weight. You have to return the max weight in the binary tree [closed]给定一棵二叉树,其中每个节点都有一定的权重。您必须返回二叉树中的最大权重 [关闭]
【发布时间】:2014-10-21 16:52:40
【问题描述】:

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

最大权重 = 根节点的值 + 其左子树和右子树的值。

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

【问题讨论】:

  • 不自​​己做作业怎么学习?

标签: java c algorithm data-structures binary-tree


【解决方案1】:

用递归很容易解决,直到没有子节点。这是一个简单的例子:

weight = getWeight(rootNode)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    相关资源
    最近更新 更多