总结所有节点

时间:2008-10-23 05:26:07

标签: c# recursion tree subtree

这可能是一个简单的修复 - 但我试图在二叉搜索树上将所有节点(来自Node类的Size属性)加在一起。在我的BST课程中,到目前为止,我有以下内容,但它返回0:

    private long sum(Node<T> thisNode)
    {
        if (thisNode.Left == null && thisNode.Right == null)
            return 0;
        if (node.Right == null)
            return sum(thisNode.Left);
        if (node.Left == null) 
            return sum(thisNode.Right);


        return sum(thisNode.Left) + sum(thisNode.Right);
    }

在我的Node类中,我有Data,它在给定的属性中存储Size和Name。我只是想把整个尺寸加起来。有什么建议或想法吗?

4 个答案:

答案 0 :(得分:2)

这是因为当你到达叶子节点时你返回零。您应该返回存储在该叶节点中的大小。

此外,如果您的非叶节点也有一个大小,您还需要处理它们:

private long sum(Node<T> thisNode)
{
    if (thisNode.Left == null && thisNode.Right == null)
        return thisNode.Size;
    if (node.Right == null)
        return thisNode.Size + sum(thisNode.Left);
    if (node.Left == null) 
        return thisNode.Size + sum(thisNode.Right);
    return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);
}

如果您的非叶节点没有大小,请使用:

private long sum(Node<T> thisNode)
{
    if (thisNode.Left == null && thisNode.Right == null)
        return thisNode.Size;
    if (node.Right == null)
        return sum(thisNode.Left);
    if (node.Left == null) 
        return sum(thisNode.Right);
    return sum(thisNode.Left) + sum(thisNode.Right);
}

第一个更优雅的版本是:

private long sum(Node<T> thisNode)
{
    if (thisNode == null)
        return 0;
    return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);
}

答案 1 :(得分:1)

也许你的意思

    if (thisNode.Left == null && thisNode.Right == null)
        return thisNode.Size;

答案 2 :(得分:1)

怎么样

private long Sum(Node<T> thisNode)
{
  if( thisNode == null )
    return 0;

  return thisNode.Size + Sum(thisNode.Left) + Sum(thisNode.Right);
}

如果size属性不在节点本身上,那么这个呢?

    public class Node<T>
    {
        public T Data;
        public Node<T> Left;
        public Node<T> Right;

        public static void ForEach(Node<T> root, Action<T> action)
        {
            action(root.Data);

            if (root.Left != null)
                ForEach(root.Left, action);
            if (root.Right != null)
                ForEach(root.Right, action);
        }
    }

    public interface IHasSize
    {
        long Size { get; }
    }

    public static long SumSize<T>(Node<T> root) where T : IHasSize
    {
        long sum = 0;
        Node<T>.ForEach(root, delegate(T item)
        {
            sum += item.Size;
        });
        return sum;
    }

答案 3 :(得分:1)

试试这个:

    private long sum(Node<T> thisNode)
    {
        if (thisNode == null)
            return 0;
        return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);
    }

原始代码返回的唯一“值”是0 - 这就是结果始终为0的原因。

相关问题