DFS 与 BFS

  • DFS:Depth-First-Search 深度优先搜索
  • BFS:Breadth-First Search 广度优先搜索 ```csharp using System; using System.Collections.Generic; using System.Linq;

namespace ConsoleTemp { // 注:为了方便理解,很多变量命名都用的全称 class Program { static void Main(string[] args) { // 生成 [0,10) 的自然数数组 var values = Enumerable.Range(0, 10).ToArray(); var binarySearchTree = GetTree(values, 0, values.Length - 1); DFS(binarySearchTree); Console.WriteLine(“============================”); BFS(binarySearchTree); }

  1. static Node GetTree(int[] values, int lowIndex, int highIndex)
  2. {
  3. if (lowIndex > highIndex) return null;
  4. var middleIndex = lowIndex + (highIndex - lowIndex) / 2;
  5. var node = new Node(values[middleIndex]);
  6. node.Left = GetTree(values, lowIndex, middleIndex - 1);
  7. node.Right = GetTree(values, middleIndex + 1, highIndex);
  8. return node;
  9. }
  10. static void DFS(Node node)
  11. {
  12. if (node == null) return;
  13. DFS(node.Left);
  14. Console.WriteLine(node.Value);
  15. DFS(node.Right);
  16. }
  17. static void BFS(Node root)
  18. {
  19. var q = new Queue<Node>();
  20. q.Enqueue(root);
  21. while (q.Count > 0)
  22. {
  23. var node = q.Dequeue();
  24. Console.WriteLine(node.Value);
  25. if (node.Left != null) q.Enqueue(node.Left);
  26. if (node.Right != null) q.Enqueue(node.Right);
  27. }
  28. }
  29. }
  30. class Node
  31. {
  32. public int Value { get; set; }
  33. public Node Left { get; set; }
  34. public Node Right { get; set; }
  35. public Node(int value)
  36. {
  37. Value = value;
  38. }
  39. }

} ``` 二叉树 - 图1