2008-10-23 131 views
1

這可能是一個簡單的修復 - 但我試圖將二叉搜索樹上的所有節點(來自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); 
    } 

在我的節點類我有數據存儲大小和名稱在他們給出的屬性。我只是想總結整個尺寸。任何建議或想法?

回答

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); 
} 

A中的第一個更優雅的版本是:

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

節點類不包含尺寸屬性 - 而不是它位於我調用並在窗體上實例化的另一個類中。 例如在窗體上我會:NameAndSize obj_NS = new NameAndSize(「Name」,320); 然後在表單中我會調用sum()返回所有對象大小的總和。 – nightdev 2008-10-23 05:41:02

1

也許你的意思

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

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; 
    } 
1

試試這個:

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

唯一的「價值」,原來的代碼永遠返回是0 - 這就是爲什麼結果總是0