本人用C#实现了一个二叉树类。封装了二叉树结构,实现方便创建一棵二叉树,并且可以对二叉树实现层序遍历,前序遍历,中序遍历以及后序遍历。控件dll将在过几天发上来共享。以下是实现的源代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace SystemLibrary
{
namespace DataStruct
{
/// <summary>
/// 链表类
/// </summary>
/// <typeparam name="T"></typeparam>
public class LinkList<T>
{
List<T> list;
/// <summary>
/// 默认
/// </summary>
public LinkList()
{
list = new List<T>();
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public LinkList(T[] value)
{
list = new List<T>(value.Length * 2);
for (int i = 0; i < value.Length; i++)
{
list[i] = value[i];
}
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public void Add(T value)
{
list.Add(value);
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <param name="value"></param>
public void Insert(int index,T value)
{
list.Insert(index, value);
}
/// <summary>
///
/// </summary>
public int Length
{
get
{
return list.Count;
}
}
/// <summary>
///
/// </summary>
public void DeleteAll()
{
list.Clear();
}
}
/// <summary>
/// 二叉树
/// </summary>
/// <typeparam name="T"></typeparam>
public class BinaryTree<T>
{
List<BinaryTreeNode<T>> tree = new List<BinaryTreeNode<T>>();
/// <summary>
/// 构建一棵空树
/// </summary>
public BinaryTree()
{
}
/// <summary>
/// 输入根节点的构造函数
/// </summary>
/// <param name="root">根节点的值</param>
public BinaryTree(T root)
{
BinaryTreeNode<T> tn = new BinaryTreeNode<T>(root);
tree.Add(tn);
}
/// <summary>
/// 对二叉树添加节点,不能在根节点之上添加
/// </summary>
/// <param name="node">要添加节点的值</param>
/// <param name="Parent">此节点的父节点的值</param>
/// <param name="td">添加的方向,是左节点还是右节点</param>
public void Add(T node, T Parent, TreeDirection td)
{
int findex = GetIndex(Parent);
int index = tree.Count;
// tree.Add(new TreeNode<T>(node));
BinaryTreeNode<T> TempNode = new BinaryTreeNode<T>(node);
if (td == TreeDirection.Left)
{
if (tree[findex].LeftChildIndex == -1)//找到未用左节点
{
tree[findex].LeftChildIndex = index;
TempNode.ParentIndex = findex;
}
else//找到已用左节点
{
int dindex = tree[findex].LeftChildIndex;
BinaryTreeNode<T> tn = tree[dindex];//获取子节点
tn.ParentIndex = index;//断开原来连接,创建新连接
TempNode.ParentIndex = findex;
TempNode.LeftChildIndex = dindex;
tree[findex].LeftChildIndex = index;
}
}
else if (td == TreeDirection.Right)
{
if (tree[findex].RightChildIndex == -1)
{
tree[findex].RightChildIndex = index;
TempNode.ParentIndex = findex;
}
else//找到已用左节点
{
int dindex = tree[findex].RightChildIndex;
BinaryTreeNode<T> tn = tree[dindex];
tn.ParentIndex = index;
TempNode.ParentIndex = findex;
TempNode.RightChildIndex = dindex;
tree[findex].RightChildIndex = index;
}
}
tree.Add(TempNode);
}
/// <summary>
/// 删除一颗子树
/// </summary>
/// <param name="node"></param>
public void RemoveTree(T node)
{//未完工
if (tree.Count == 1)
{
if (tree[0].Value.Equals(node))
{
tree = new List<BinaryTreeNode<T>>();
}
return;
}
bool[] temp = new bool[tree.Count];
for (int i = 0; i < temp.Length; i++)
{
temp[i] = true;
}
for (int i = 0; i < tree.Count; i++)
{
if (tree[i].Value.Equals(node))
{
int parentIndex = tree[i].ParentIndex;
int leftIndex = tree[i].LeftChildIndex;
int rightIndex = tree[i].RightChildIndex;
if (parentIndex != -1)
{
if (tree[parentIndex].LeftChildIndex == i)
{
tree[parentIndex].LeftChildIndex = -1;
}
else if (tree[parentIndex].RightChildIndex == i)
{
tree[parentIndex].RightChildIndex = -1;
}
else
{
throw new Exception("出意外,行127");
}
temp[i] = false;
Stack<int> stack = new Stack<int>();
if (leftIndex != -1) stack.Push(leftIndex);
if (rightIndex != -1) stack.Push(rightIndex);
while (stack.Count != 0)
{
int p = stack.Pop();
temp[p] = false;
if (tree[p].LeftChildIndex != -1)
stack.Push(tree[p].LeftChildIndex);
if (tree[p].RightChildIndex != -1)
stack.Push(tree[p].RightChildIndex);
}
}
break;
}
}
List<BinaryTreeNode<T>> list = new List<BinaryTreeNode<T>>();
for (int i = 0; i < tree.Count; i++)
{
if (temp[i])
list.Add(tree[i]);
}
tree = list;
}
/// <summary>
/// 找值为node的节点的下标
/// </summary>
/// <param name="node">需要找的值</param>
/// <returns>找不到返回-1</returns>
private int GetIndex(T node)
{
for (int i = 0; i < tree.Count; i++)
{
if (tree[i].Value.Equals(node))
return i;
}
return -1;
}
/// <summary>
/// 自定义ToString,以数组形式表示树
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tree.Count; i++)
{
BinaryTreeNode<T> tn = tree[i];
sb.Append(string.Format("{0} {1} {2} {3}", tn.ParentIndex, tn.Value, tn.LeftChildIndex, tn.RightChildIndex));
sb.Append("/r/n");
}
return sb.ToString();
//return base.ToString();
}
/// <summary>
/// 中序遍历二叉树,返回元素序列
/// </summary>
/// <returns></returns>
public string InOrderTraverse()
{
if (tree.Count == 0) return "";
Stack<int> stack = new Stack<int>();
List<T> buffer = new List<T>();
int p = 0;
while (p != -1 || stack.Count != 0)
{
if (p != -1)
{
stack.Push(p);
p = tree[p].LeftChildIndex;
}
else
{
int index = stack.Pop();
buffer.Add(tree[index].Value);
p = tree[index].RightChildIndex;
}
}
return PrintBuffer(buffer);
}
/// <summary>
/// 前序遍历二叉树,返回元素序列
/// </summary>
/// <returns></returns>
public string PreOrderTraverse()
{
if (tree.Count == 0) return "";
Stack<int> stack = new Stack<int>();
List<T> buffer = new List<T>();
int p = 0;
while (p != -1 || stack.Count != 0)
{
if (p != -1)
{
buffer.Add(tree[p].Value);
stack.Push(p);
p = tree[p].LeftChildIndex;
}
else
{
int index = stack.Pop();
p = tree[index].RightChildIndex;
}
}
return PrintBuffer(buffer);
}
/// <summary>
/// 后序遍历二叉树,返回元素序列
/// </summary>
/// <returns></returns>
public string PostOrderTraverse()
{
if (tree.Count == 0) return "";
Stack<int> stack = new Stack<int>();
List<int> buffer = new List<int>();
int p = 0;
while (p != -1 || stack.Count != 0)
{
if (p != -1)
{
stack.Push(p);
p = tree[p].LeftChildIndex;
}
else
{
int index = stack.Pop();
p = tree[index].RightChildIndex;
bool b = IsIn(buffer, index);
if (p == -1 && !b)
{
// stack.Pop();
buffer.Add(index);
}
else if (IsIn(buffer, p) && !b)
{
buffer.Add(index);
p = -1;
}
else
stack.Push(index);
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Count; i++)
{
if (i < buffer.Count - 1)
sb.Append(tree[buffer[i]].Value.ToString() + ",");
else
sb.Append(tree[buffer[i]].Value);
}
return sb.ToString();
}
/// <summary>
/// 层序遍历二叉树,返回元素序列
/// </summary>
/// <returns></returns>
public string LevelOrderTraverse()
{
Queue<int> queue = new Queue<int>();
StringBuilder sb = new StringBuilder();
if (tree.Count == 0)
return "";
sb.Append(tree[0].Value.ToString() + ",");
if (tree[0].LeftChildIndex != -1)
{
queue.Enqueue(tree[0].LeftChildIndex);
}
if (tree[0].RightChildIndex != -1)
{
queue.Enqueue(tree[0].RightChildIndex);
}
while (queue.Count != 0)
{
int a = queue.Dequeue();
sb.Append(tree[a].Value.ToString() + ",");
if (tree[a].LeftChildIndex != -1)
queue.Enqueue(tree[a].LeftChildIndex);
if (tree[a].RightChildIndex != -1)
queue.Enqueue(tree[a].RightChildIndex);
}
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
/// <summary>
/// 按先序序列建立一棵二叉树
/// </summary>
/// <param name="v"></param>
public void CreateBiTreeInPre(string v)
{
/* if (tree.Count != 0)
{
throw new Exception("必须要在一棵空树上建");
}*/
char[] split = new char[] { ',', ' ', '/r' };
string[] s = v.Split(split);
List<string> list = new List<string>();
for (int i = 0; i < s.Length; i++)
{
if (s[i] != "")
{
list.Add(s[i]);
}
}
s = list.ToArray(); list = null;
if (s == null && s.Length == 0)
return;
T vat = default(T);
try
{
vat = (T)Convert.ChangeType(s[0], typeof(T));
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
}
BinaryTreeNode<T> tn = new BinaryTreeNode<T>(vat);
tree.Add(tn);
Stack<T> stack = new Stack<T>();
Stack<byte> byteStack = new Stack<byte>();
Stack<byte> directionStack = new Stack<byte>();
stack.Push(vat);
byteStack.Push(Convert.ToByte(0));
directionStack.Push(Convert.ToByte(0));//0是左,1是右
for (int i = 1; i < s.Length; i++)
{
string p = s[i].ToLower();
switch (p)
{
case "null":
byte b = byteStack.Pop();
b += Convert.ToByte(1);
if (b < 2)
byteStack.Push(b);
else
{
stack.Pop();
directionStack.Pop();
}
break;
default:
T vat1 = stack.Peek();
///
byte b1 = byteStack.Pop();
b1 += Convert.ToByte(1);
if (b1 < 2)
byteStack.Push(b1);
///
byte direct = directionStack.Pop();
if (direct == 0)
{
Add((T)Convert.ChangeType(s[i], typeof(T)), /*(T)Convert.ChangeType(s[i - 1], typeof(T))*/vat1, TreeDirection.Left);
}
else
Add((T)Convert.ChangeType(s[i], typeof(T)), /*(T)Convert.ChangeType(s[i - 1], typeof(T))*/vat1, TreeDirection.Right);
direct += Convert.ToByte(1);
directionStack.Push(direct);
stack.Push((T)Convert.ChangeType(s[i], typeof(T)));
byteStack.Push(Convert.ToByte(0));
directionStack.Push(Convert.ToByte(0));
break;
}
}
}
/// <summary>
/// 按层序遍历建立一棵二叉树
/// </summary>
/// <param name="v"></param>
public void CreateBiTreeInLayer(string v)
{
char[] split = new char[] { ',', ' ', '/r' };
string[] s = v.Split(split);
List<string> list = new List<string>();
for (int i = 0; i < s.Length; i++)
{
if (s[i] != "")
{
list.Add(s[i]);
}
}
s = list.ToArray(); list = null;
if (s == null && s.Length == 0)
return;
int currentOfLayers = 0;
if (tree.Count != 0)
{
throw new Exception("cannot setup tree");
}
Queue<T> queue = new Queue<T>();
for (int i = 0; i < s.Length; i++)
{
int n = Convert.ToInt32(Math.Pow(2, currentOfLayers));
int j = n;
bool direction = true;//true为左,false为右
int p = 0;
while (true)
{
if (tree.Count == 0)
{
T vat = (T)Convert.ChangeType(s[i], typeof(T));
tree.Add(new BinaryTreeNode<T>(vat));
queue.Enqueue(vat);
}
else
{
T val = default(T);
if (p < 1)
{
val = queue.Peek();
p++;
}
else
{
val = queue.Dequeue();
p = 0;
}
if (direction)
{
if (s[i].ToLower() != "null")
{
T t1 = (T)Convert.ChangeType(s[i], typeof(T));
Add(t1, val, TreeDirection.Left);
queue.Enqueue(t1);
}
}
else
{
if (s[i].ToLower() != "null")
{
T t2 = (T)Convert.ChangeType(s[i], typeof(T));
Add(t2, val, TreeDirection.Right);
queue.Enqueue(t2);
}
}
direction = !direction;
}
j--;
if (j > 0 && i < s.Length - 2)
i++;
else
break;
}
currentOfLayers++;
}
}
/// <summary>
/// 返回结点数
/// </summary>
public int Count
{
get { return tree.Count; }
}
/* /// <summary>
/// 根据节点个数,返回树的层数
/// </summary>
/// <param name="m">节点的个数</param>
/// <returns></returns>
static int GetLayerNums(int m)
{
return Convert.ToInt32(Math.Floor(Math.Log(Convert.ToDouble(m + 1), 2.0)))+1;
}*/
private bool IsIn(List<int> buffer, int p)
{
for (int i = 0; i < buffer.Count; i++)
if (buffer[i] == p)
return true;
return false;
}
private string PrintBuffer(List<T> buffer)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Count; i++)
{
if (i < buffer.Count - 1)
{
sb.Append(buffer[i].ToString() + ",");
}
else
{
sb.Append(buffer[i].ToString());
}
}
return sb.ToString();
}
}
internal class BinaryTreeNode<T>
{
private T value;
private int leftchild;
private int rightchild;
private int parent;
public BinaryTreeNode(T value)
{
this.value = value;
leftchild = -1;
rightchild = -1;
parent = -1;
}
/// <summary>
/// 获取或设置节点的值
/// </summary>
public T Value
{
get
{
return value; ;
}
set { this.value = value; }
}
/// <summary>
/// 获取或设置节点的左孩子节点的下标
/// </summary>
public int LeftChildIndex
{
get { return leftchild; }
set { leftchild = value; }
}
/// <summary>
/// 获取或设置节点的右孩子节点的下标
/// </summary>
public int RightChildIndex
{
get { return rightchild; }
set { rightchild = value; }
}
/// <summary>
/// 获取或设置父节点的下标
/// </summary>
public int ParentIndex
{
get { return parent; }
set { parent = value; }
}
}
/// <summary>
/// 树的方向
/// </summary>
public enum TreeDirection
{
/// <summary>
/// 向左
/// </summary>
Left,
/// <summary>
/// 向右
/// </summary>
Right
}
}
}