vencinachev

Tree

Sep 8th, 2019
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. class Tree<T>
  2.     {
  3.         private TreeNode<T> root;
  4.  
  5.         public Tree(T value)
  6.         {
  7.             this.root = new TreeNode<T>(value);
  8.         }
  9.  
  10.         public Tree(T value, params Tree<T>[] children) : this(value)
  11.         {
  12.             foreach(Tree<T> child in children)
  13.             {
  14.                 this.root.AddChild(child.root);
  15.             }
  16.         }
  17.  
  18.         public TreeNode<T> Root
  19.         {
  20.             get
  21.             {
  22.                 return this.root;
  23.             }
  24.         }
  25.  
  26.         // Breadth-First-Search - (BFS)
  27.         public void PrintBFS()
  28.         {
  29.             Queue<TreeNode<T>> visited = new Queue<TreeNode<T>>();
  30.             visited.Enqueue(this.root);
  31.             while (visited.Count != 0)
  32.             {
  33.                 TreeNode<T> current = visited.Dequeue();
  34.                 Console.Write(current.Value + " ");
  35.                 for (int i = 0; i < current.ChildrenCount; i++)
  36.                 {
  37.                     visited.Enqueue(current.GetChild(i));
  38.                 }
  39.             }
  40.         }
  41.  
  42.         // Depth-First-Search (DFS)
  43.         public void PrintDFS()
  44.         {
  45.             Stack<TreeNode<T>> visited = new Stack<TreeNode<T>>();
  46.             visited.Push(this.root);
  47.             while (visited.Count != 0)
  48.             {
  49.                 TreeNode<T> current = visited.Pop();
  50.                 Console.Write(current.Value + " ");
  51.                 for (int i = 0; i < current.ChildrenCount; i++)
  52.                 {
  53.                     visited.Push(current.GetChild(i));
  54.                 }
  55.             }
  56.         }
  57.     }
Add Comment
Please, Sign In to add comment