2022-12-23 18:28:17 +08:00
|
|
|
|
/**
|
|
|
|
|
* File: binary_tree_bfs.cs
|
|
|
|
|
* Created Time: 2022-12-23
|
|
|
|
|
* Author: haptear (haptear@hotmail.com)
|
|
|
|
|
*/
|
|
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
|
namespace hello_algo.chapter_tree;
|
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public class binary_tree_bfs {
|
2022-12-23 15:42:02 +08:00
|
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
|
/* 层序遍历 */
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public List<int> levelOrder(TreeNode root) {
|
2023-04-09 04:32:17 +08:00
|
|
|
|
// 初始化队列,加入根节点
|
2023-02-08 22:18:02 +08:00
|
|
|
|
Queue<TreeNode> queue = new();
|
|
|
|
|
queue.Enqueue(root);
|
|
|
|
|
// 初始化一个列表,用于保存遍历序列
|
|
|
|
|
List<int> list = new();
|
2023-04-23 03:03:12 +08:00
|
|
|
|
while (queue.Count != 0) {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
TreeNode node = queue.Dequeue(); // 队列出队
|
2023-04-09 04:32:17 +08:00
|
|
|
|
list.Add(node.val); // 保存节点值
|
2023-02-08 22:18:02 +08:00
|
|
|
|
if (node.left != null)
|
2023-04-09 04:32:17 +08:00
|
|
|
|
queue.Enqueue(node.left); // 左子节点入队
|
2023-02-08 22:18:02 +08:00
|
|
|
|
if (node.right != null)
|
2023-04-09 04:32:17 +08:00
|
|
|
|
queue.Enqueue(node.right); // 右子节点入队
|
2022-12-23 15:42:02 +08:00
|
|
|
|
}
|
2023-02-08 22:18:02 +08:00
|
|
|
|
return list;
|
|
|
|
|
}
|
2022-12-23 15:42:02 +08:00
|
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
|
[Test]
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public void Test() {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
/* 初始化二叉树 */
|
|
|
|
|
// 这里借助了一个从数组直接生成二叉树的函数
|
2023-04-21 14:59:22 +08:00
|
|
|
|
TreeNode? root = TreeNode.ListToTree(new List<int?> { 1, 2, 3, 4, 5, 6, 7 });
|
2023-02-08 22:18:02 +08:00
|
|
|
|
Console.WriteLine("\n初始化二叉树\n");
|
|
|
|
|
PrintUtil.PrintTree(root);
|
2022-12-24 16:15:41 +08:00
|
|
|
|
|
2023-02-15 03:36:22 +08:00
|
|
|
|
List<int> list = levelOrder(root);
|
2023-04-21 14:59:22 +08:00
|
|
|
|
Console.WriteLine("\n层序遍历的节点打印序列 = " + string.Join(",", list));
|
2022-12-23 15:42:02 +08:00
|
|
|
|
}
|
|
|
|
|
}
|