博客中代码都经过运行并且没有bug
二叉链表数据结构和二叉链表的构造
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 树
{
class 二叉链表
{
/// <summary>
/// 二叉链表结点结构
/// </summary>
public class BiTNode
{
public char data;
public BiTNode lchild,rchild;//左右孩子指针
}
/// <summary>
/// 构造二叉树
/// </summary>
/// <returns></returns>
public static BiTNode InitBiTree()
{
BiTNode biTNodeA = new BiTNode() { data = 'A' };
BiTNode biTNodeB = new BiTNode() { data = 'B' };
BiTNode biTNodeC = new BiTNode() { data = 'C' };
BiTNode biTNodeD = new BiTNode() { data = 'D' };
BiTNode biTNodeE = new BiTNode() { data = 'E' };
BiTNode biTNodeF = new BiTNode() { data = 'F' };
BiTNode biTNodeG = new BiTNode() { data = 'G' };
BiTNode biTNodeH = new BiTNode() { data = 'H' };
BiTNode biTNodeK = new BiTNode() { data = 'K' };
biTNodeA.lchild = biTNodeB;
biTNodeA.rchild = biTNodeE;
biTNodeB.lchild = null;
biTNodeB.rchild = biTNodeC;
biTNodeC.lchild = biTNodeD;
biTNodeC.rchild = null;
biTNodeD.lchild = null;
biTNodeD.rchild = null;
biTNodeE.lchild = null;
biTNodeE.rchild = biTNodeF;
biTNodeF.lchild = biTNodeG;
biTNodeF.rchild = null;
biTNodeG.lchild = biTNodeH;
biTNodeG.rchild = biTNodeK;
biTNodeH.lchild = null;
biTNodeH.rchild = null;
biTNodeK.lchild = null;
biTNodeK.rchild = null;
return biTNodeA;
}
}
}
递归实现中序遍历
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 树
{
class 中序遍历_递归_
{
/// <summary>
/// 递归实现中序遍历
/// </summary>
public static void midOrderTraverse(二叉链表.BiTNode T)
{
if (T.lchild != null)
{
midOrderTraverse(T.lchild);
}
if (T != null)
{
Console.Write(T.data+" ");
}
if (T.rchild != null)
{
midOrderTraverse(T.rchild);
}
}
}
}
非递归实现中序遍历
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 树
{
class 中序遍历_非递归_
{
/// <summary>
/// 非递归中序遍历的算法
/// </summary>
/// <param name="T"></param>
public static void midOrderTraverse(二叉链表.BiTNode T)
{
Stack<二叉链表.BiTNode> stack = new Stack<二叉链表.BiTNode>();
二叉链表.BiTNode t = GoFarLeft(T,stack);//找到最左下的结点
while (t != null)
{
Console.Write(t.data+" ");
if (t.rchild != null)
{
t = GoFarLeft(t.rchild, stack);
}
else if (stack.Count > 0)//栈不空时退栈
{
t = stack.Pop();
}
else
{
t = null;//栈空表明遍历结束
}
}
}
public static 二叉链表.BiTNode GoFarLeft(二叉链表.BiTNode T, Stack<二叉链表.BiTNode> s)
{
if (T == null)
{ return null; }
while (T.lchild != null)
{
s.Push(T);
T = T.lchild;
}
return T;
}
}
}
//运行二叉树遍历算法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 树
{
class Program
{
static void Main(string[] args)
{
二叉链表.BiTNode T = 二叉链表.InitBiTree();
//中序遍历_递归_.midOrderTraverse(T);
中序遍历_非递归_.midOrderTraverse(T);
Console.ReadKey();
}
}
}