C#实现二叉树的层次遍历
本文讲解C#实现二叉树的层次遍历
1、 /// 层次遍历
///
/// 层次遍历
///
///
static void LevelOrder(BiTNode T) {
SqQueue Q = new SqQueue();
Q.data = new BiTNode[MaxSize];
InitQueue(ref Q);
BiTNode p = null;
EnQueue(ref Q, T);
while (!isEmpty(Q)) {
DeQueue(ref Q, ref p);
visit§;
if (p.lchild!=null) { EnQueue(ref Q, p.lchild); }
if (p.rchild!=null) { EnQueue(ref Q,p.rchild); }
}
}
2、节点值访问
///
/// 结点值的输出
///
static void visit(BiTNode T) {
Console.Write(T.data+" ");
}
3、队列结构
///
/// 队列结构体定义
///
public struct SqQueue
{
public BiTNode[] data;//队列存放的元素
public int front, real;//队头和队尾指针
}
///
/// 队列初始化
///
///
static void InitQueue(ref SqQueue Q)
{
Q.real = Q.front = 0;
}
///
/// 判断队列是否为空
///
///
///
static bool isEmpty(SqQueue Q)
{
if (Q.front == Q.real) { return true; }
else return false;
}
///
/// 入队
///
///
///
///
static bool EnQueue(ref SqQueue Q, BiTNode x)
{
if ((Q.real + 1) % MaxSize == Q.front) { return false; }
Q.data[Q.real] = x;
Q.real = (Q.real + 1) % MaxSize;
return true;
}
///
/// 出队
///
///
///
///
static bool DeQueue(ref SqQueue Q, ref BiTNode x)
{
if (Q.real == Q.front) { return false; }
x = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
4、实际main函数测试
public const int MaxSize = 50;
static void Main(string[] args)
{
BiTNode T = new BiTNode() ;
int x=0;
//创建二叉树
T.data = 1;
T.lchild= new BiTNode();
T.lchild.data = 2;
T.rchild = new BiTNode();
T.rchild.data = 3;
T.lchild.rchild=new BiTNode();
T.lchild.rchild.data = 4;
T.lchild.rchild.lchild= new BiTNode();
T.lchild.rchild.lchild.data = 6;
T.rchild.rchild = new BiTNode();
T.rchild.rchild.data = 5;
Console.WriteLine(“先序遍历的值:”);
PreOrder(T);
Console.WriteLine();
Console.WriteLine(“中序遍历的值:”);
InOrder(T);
Console.WriteLine();
Console.WriteLine(“后序遍历的值:”);
PostOrder(T);
Console.WriteLine();
Console.WriteLine(“非递归中序遍历的值:”);
InOrder2(T);
Console.WriteLine();
Console.WriteLine(“层次遍历的值:”);
LevelOrder(T);
Console.ReadLine();
}
相关文章
- C#下载csv代码总结(解决中文乱码问题)
- Find or Query Data with C# Driver
- [翻译] C# 8.0 新特性 Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南) 【由浅至深】redis 实现发布订阅的几种方式 .NET Core开发者的福音之玩转Redis的又一傻瓜式神器推荐
- WPF中的常用布局 栈的实现 一个关于素数的神奇性质 C# defualt关键字默认值用法 接口通俗理解 C# Json序列化和反序列化 ASP.NET CORE系列【五】webapi整理以及RESTful风格化
- Word控件Spire.Doc 【文本】教程(3) ;在 C#、VB.NET 中的 Word 中查找和突出显示文本
- Word控件Spire.Doc 转换教程(二十七):如何在 C# 中将 Word 转换为 PostScript
- c# .net 怎么让生成的DLL有注释
- C#从入门到精通(第4版) 明日科技 随书视频光盘+源码[1.6G]
- Window捕获消息机制-C#
- c#中已知一个外部窗口的句柄,怎么关闭
- 你是否有遇到过某个实体类字段(属性)过多的情况,不想每次点的话戳进来(C# 反射)
- C#获取汉字字符串拼音首字母的方法(转载)
- C# 算法之链表、双向链表以及正向反向遍历实现
- C# Xamarin移动开发项目实战篇
- C#-类和结构(C# 编程指南)
- c#JSON序列化&反序列化