自定义Tree结构类
public class MyNode { private object _name; private MyNode _left; private MyNode _right; public MyNode(object name) { _name = name; } public object Name { get { return _name; } } public MyNode Left { get { return _left; } set { _left = value;} } public MyNode Right { get { return _right; } set { _right = value; } } public override string ToString() { return _name.ToString(); } } public class MyBinaryTree { private MyNode _heard;//指针 private string cStr;//构造二叉树字符串 public MyBinaryTree(string constructCstr) { cStr = constructCstr; if (cStr.Length > 0) { _heard = new MyNode(cStr[0]); this.Add(_heard, 0); } } public void Add(MyNode myNode, int index) { int leftIndex = 2 * index + 1; if (leftIndex < cStr.Length) { myNode.Left = new MyNode(cStr[leftIndex]); this.Add(myNode.Left, leftIndex); } int rightIndex = 2 * index + 2; if (rightIndex < cStr.Length) { myNode.Right = new MyNode(cStr[rightIndex]); this.Add(myNode.Right, rightIndex); } } #region propety public MyNode Heard { get {return _heard; } } #endregion #region Method public void PreOrder(MyNode node) //先序遍历 { if (node != null) { Console.Write(node.ToString()); //打印字符 PreOrder(node.Left); //递归 PreOrder(node.Right); //递归 } } public void MidOrder(MyNode node) //中序遍历 { if (node != null) { MidOrder(node.Left); //递归 Console.Write(node.ToString()); //打印字符 MidOrder(node.Right); //递归 } } public void AfterOrder(MyNode node) //后继遍历 { if (node != null) { AfterOrder(node.Left); //递归 AfterOrder(node.Right); //递归 Console.Write(node.ToString()); //打印字符 } } public void LevelOrder() //宽度优先遍历 { Queue queue = new Queue(); //声明一个队例 queue.Enqueue(_head); //把根结点压入队列 while (queue.Count > 0) //只要队列不为空 { Node node = (Node)queue.Dequeue(); //出队 Console.Write(node.ToString()); //访问结点 if (node.Left != null) //如果结点左孩子不为空 { //把左孩子压入队列 queue.Enqueue(node.Left); } if (node.Right != null) //如果结点右孩子不为熔 { //把右孩子压入队列 queue.Enqueue(node.Right); } } } #endregion }
MyBinaryTree myBinaryTree = new MyBinaryTree("ABCDE#F"); myBinaryTree.PreOrder(myBinaryTree.Heard); myBinaryTree.MidOrder(myBinaryTree.Heard); myBinaryTree.AfterOrder(myBinaryTree.Heard); //使用字符串构造二叉树 myBinaryTree.LevelOrder();
参考:
二叉树结点类http://www.cnblogs.com/abatei/archive/2008/05/23/1205707.html