缺陷鉴于像哪里是我的线性算法
class Node
{
public int Val { get; set; }
public Node Parent { get; set; }
public List<Node> Children { get; set; } = new List<Node>();
/// <summary>
/// Sum of values in descendant nodes
/// </summary>
public int DescendantsSum { get; set; } = 0;
/// <summary>
/// Sum of values in tree whose root is this node
/// </summary>
public int TreeSum { get { return Val + DescendantsSum; } }
}
节点和Node
s的Val
S作设定的树,我想要做的是什么是在描述下面的方法总结我写
/// <summary>
/// Given a tree like
///
/// Val=100
/// \
/// Val=200
/// / \
/// / Val=100
/// Val=100
/// / \
/// Val=500 Val=600
///
/// set a field for each node showing the sum of the values
/// in the subtree whose root is that node, making it into
///
/// Val=100
/// Sum=1600
/// \
/// Val=200
/// Sum=1500
/// / \
/// / Val=100
/// / Sum=100
/// Val=100
/// Sum=1200
/// / \
/// Val=500 Val=600
/// Sum=500 Sum=600
///
/// </summary>
static void SetSums(Node[] nodes)
{
foreach(var leaf in nodes.Where(node => node.Children.Count == 0))
for(var cur = leaf; cur.Parent != null; cur = cur.Parent)
cur.Parent.DescendantsSum += cur.TreeSum;
}
然而,这导致像3400
错误地大值,其中应该1600
。我想过我的算法,我看不出它有什么缺陷。任何提示?
完全同意...从上到下更有意义,并且将一组节点作为参数的SetSums方法是完全不必要的。 – user1796440