树结构类别总和级联到根节点

时间:2009-12-04 07:39:46

标签: recursion tree hierarchical-trees

我会马上出来说我不是世界上最伟大的数学家:D所以这个问题对大多数人来说可能很简单。不幸的是,这令我感到困惑,并且在可行的解决方案上有过几次尝试。

与任何树一样,可以有许多分支,许多分支可以有更多的分支,依此类推,直到它们以叶节点结束。我已经获得了每张叶子的信息,表明它的价值。

我需要的是如何解决将每个叶节点值总结为其分支(父节点)的总和以及对其余节点执行相同操作的问题的明确探索,但不要忘记如果分支由其他分支共享它是与自身直接相关的每个较低级别分支和叶子的摘要。

为了更好地解释:

Root
|----Branch
|         |-Leaf 10
|----Branch
|         |----Branch
|         |-Leaf 20 |-Leaf 30
|----Branch         |-Leaf 40
|         |----Branch
|                   |----Branch
|                             |----Leaf 50
|-Leaf 60

目标:

Root 210
|----Branch 10
|         |-Leaf 10
|----Branch 90
|         |----Branch 70
|         |-Leaf 20 |-Leaf 30
|----Branch 50      |-Leaf 40
|         |----Branch 50
|                   |----Branch 50
|                             |----Leaf 50
|-Leaf 60

我能够识别最低级别的成员(叶子节点),根节点和分支本身。我没有关于分支是否有其他分支链接到自身下部或直接链接到叶节点的标识。这种关系在根本上是自下而上的。 IE:该分支没有提及它的孩子是谁,但孩子们知道父母是谁。

如果有什么不清楚请问,我会尝试更好地解释问题。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

好的,左手给了这个刺。

我会用一些伪代码

这样做
foreach leaf in knownLeafs
    parent = leaf.parent //get the leaf parent
    parent.total = parent.total + leaf.value //add leaf value to parent total
    while parent.parent != null //loop until no more parents, this would be the root
    {
        current = parent
        parent = parent.parent //move up the structure
        parent.total = parent.total + current.total
    }
next leaf

你需要创建一个函数,给定一个节点,返回父节点

节点GetParentNodeFrom(节点)

新的伪代码看起来像这样

foreach leaf in knownLeafs
parent = GetParentNodeFrom(leaf) //get the leaf parent

parent.total = parent.total + leaf.value //add leaf value to parent total
while GetParentNodeFrom(parent) != null //loop until no more parents, this would be the root
{
    current = parent
    parent = GetParentNodeFrom(current) //move up the structure
    parent.total = parent.total + current.total
}
next leaf

抱歉,我的错误,你应该只移动叶子值,而不是总数。 请参阅使用的新leafValue。

foreach leaf in knownLeafs
parent = GetParentNodeFrom(leaf) //get the leaf parent
leafValue = leaf.value
parent.total = parent.total + leafValue //add leaf value to parent total
while GetParentNodeFrom(parent) != null //loop until no more parents, this would be the root
{
    current = parent
    parent = GetParentNodeFrom(current) //move up the structure
    parent.total = parent.total + leafValue
}
next leaf

答案 1 :(得分:0)

您想确定树中所有节点的总和吗?

树行走有助于提供优雅的递归解决方案:

public int SumTree (TreeNode n) {
    if(n.isLeafNode) return n.value;
    return SumTree(n.left) + SumTree(n.right);
}

假设一棵二叉树。