C#实现DFS和BFS

以图示为例:

Node root = new Node("A",
                new Node("B",
                    new Node("C"), new Node("D")), 
                new Node("E",
                    new Node("F"), new Node("G",
                                    null, new Node("H"))));

DFS:

  public static void DFS(Node root)
  {
      Stack<Node> stack = new Stack<Node>();
      stack.Push(root);

      while (stack.Count > 0)
      {
          Node node = stack.Pop();
          Console.Write(node.Value + " ");

          if (node.Right != null)
          {
              stack.Push(node.Right);
          }

          if (node.Left != null)
          {
              stack.Push(node.Left);
          }
      }
  }

  public static void DFS_Recursion(Node root)
  {
      if (root == null)
          return;

      Console.Write(root.Value + " ");

      DFS_Recursion(root.Left);
      DFS_Recursion(root.Right);
  }

BFS:

  public static void BFS(Node root)
  {
      Queue<Node> queue = new Queue<Node>();
      queue.Enqueue(root);

      while (queue.Count > 0)
      {
          Node node = queue.Dequeue();
          Console.Write(node.Value + " ");

          if (node.Left != null)
          {
              queue.Enqueue(node.Left);
          }

          if (node.Right != null)
          {
              queue.Enqueue(node.Right);
          }
      }
  }

Main函数:

  Console.WriteLine("BFS:");
  BFS(root);

  Console.WriteLine("\nDFS:");
  DFS(root);

  Console.WriteLine("\nDFS_Recursion:");
  DFS_Recursion(root);

输出:

BFS:
A B E C D F G H
DFS:
A B C D E F G H
DFS_Recursion:
A B C D E F G H
posted @ 2024-07-04 17:59  二声  阅读(72)  评论(0)    收藏  举报