2016-02-21 66 views
-2

我做在C#中的基本n元樹:如何在C#中直觀地打印n-ary樹?

樹:

public class Tree<T> 
{ 
    private Node<T> root; 

    public Tree() 
    { 
     root = null; 
    } 


    public Node<T> Root 
    { 
     get 
     { 
      return root; 
     } 

     set 
     { 
      root = value; 
     } 
    } 

    public T search (T data) 
    { 
     return (root != null) ? raiz.search(data) : default(T); 
    } 

}

節點:

public class Node<T> 
{ 
    private T data; 
    private List<Node<T>> childs; 

    public Node(T data) 
    { 
     this.data = data; 
     this.childs = null; 
    } 

    public T Data 
    { 
     get 
     { 
      return data; 
     } 

     set 
     { 
      data = value; 
     } 
    } 

    public List<NodoArbol<T>> Childs 
    { 
     get 
     { 
      return childs; 
     } 

     set 
     { 
      childs = value; 
     } 
    } 

    public void addChild(Node node) 
    { 
     if (child == null) 
     { 
      childs = new List<Node<T>>(); 
     } 
      childs.Add(node); 

    } 


    public T search(T data) 
    { 
     if (this.data.Equals(data)) 
     { 
      return this.data; 
     }else 
     { 
      for (int i = 0; i < childs.Count; i++) 
      { 
       T aux = childs.ElementAt(i).search(data); 
       if (aux != null) 
       { 
        return aux; 
       } 
      } 
      return default(T); 
     } 
    } 
} 

我想樹的視覺表現這樣我就可以快速測試,看看孩子和節點是否在正確的位置,然後測試我的遍歷(預購/按順序/順序),例如:

enter image description here

+0

您是使用winforms還是WPF? –

+0

你有問題布賴恩? – Mathemats

+0

即使您提供了我們的數據結構,我們也不是代碼編寫服務 – MickyD

回答

1

如果足夠你將它輸出到控制檯:

public void PrintTree(Node node, int indentSize, int currentLevel) 
{ 
    var currentNode = string.Format("{0}{1}", new string(" ",indentSize*currentLevel, node.Data); 
    Console.WriteLine(currentNode) 
    foreach(var child in node.Children) 
    { 
     PrintTree(child, indentSize, currentLevel+1); 
    } 
} 

然後調用它像這樣

PrintTree(yourTreeInstance.Root,4,0); 

您還可以使用的Debug.WriteLine輸出到調試控制檯,而不是主控臺