下面是一個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方法進行層次遍歷。