c#二叉树的层次遍历实现方法

avatar
作者
猴君
阅读量:0

下面是一个C#实现二叉树的层次遍历的例子:

using System; using System.Collections.Generic;  public class TreeNode {     public int val;     public TreeNode left;     public TreeNode right;     public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) {         this.val = val;         this.left = left;         this.right = right;     } }  public class BinaryTree {     public List<List<int>> LevelOrder(TreeNode root) {         List<List<int>> result = new List<List<int>>();         if (root == null) {             return result;         }          Queue<TreeNode> queue = new Queue<TreeNode>();         queue.Enqueue(root);          while (queue.Count > 0) {             int levelSize = queue.Count;             List<int> levelValues = new List<int>();              for (int i = 0; i < levelSize; i++) {                 TreeNode node = queue.Dequeue();                 levelValues.Add(node.val);                  if (node.left != null) {                     queue.Enqueue(node.left);                 }                 if (node.right != null) {                     queue.Enqueue(node.right);                 }             }              result.Add(levelValues);         }          return result;     } }  class Program {     static void Main() {         TreeNode root = new TreeNode(3);         root.left = new TreeNode(9);         root.right = new TreeNode(20);         root.right.left = new TreeNode(15);         root.right.right = new TreeNode(7);          BinaryTree bt = new BinaryTree();         List<List<int>> result = bt.LevelOrder(root);          foreach (List<int> level in result) {             Console.Write("[");             foreach (int val in level) {                 Console.Write(val + " ");             }             Console.Write("]");             Console.WriteLine();         }     } } 

这段代码实现了一个二叉树的层次遍历。通过使用一个队列来辅助遍历,每次遍历一层节点,依次将它们的值存入结果列表中。最后返回结果列表。在Main函数中创建一个二叉树节点并调用LevelOrder方法进行层次遍历。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!