/// 二叉树结点类
/// </summary>
public class BinaryTreeNode
{
object _data;
BinaryTreeNode _left;
BinaryTreeNode _right;
public BinaryTreeNode Left
{
get
{
return this._left;
}
set
{
this._left = value;
}
}
public BinaryTreeNode Right
{
get
{
return this._right;
}
set
{
this._right = value;
}
}
public BinaryTreeNode(object data)
{
this._data = data;
}
public override string ToString()
{
return (null == _data)? string.Empty : _data.ToString();
}
}
/// <summary>
/// 二叉树集合类
///</summary>publicclass BinaryTree
{
BinaryTreeNode _head;
string _strBinaryTree;
public BinaryTreeNode Head
{
get
{
return this._head;
}
}
void AddNode(BinaryTreeNode parent,int index)
{
int leftIndex = index * 2 + 1;
if(leftIndex < _strBinaryTree.Length)
{
if(_strBinaryTree[leftIndex] != '*')
{
parent.Left = new BinaryTreeNode(_strBinaryTree[leftIndex]);
AddNode(parent.Left,leftIndex);
}
}
int rightIndex = index * 2 + 2;
if(rightIndex < _strBinaryTree.Length)
{
if(_strBinaryTree[rightIndex] != '*')
{
parent.Right = new BinaryTreeNode(_strBinaryTree[rightIndex]);
AddNode(parent.Right,rightIndex);
}
}
}
public void PerOrder(BinaryTreeNode node)
{
if(null != node)
{
Console.Write(node);
PerOrder(node.Left);
PerOrder(node.Right);
}
}
public void MidOrder(BinaryTreeNode node)
{
if(null != node)
{
MidOrder(node.Left);
Console.Write(node);
MidOrder(node.Right);
}
}
public void AfterOrder(BinaryTreeNode node)
{
if(null != node)
{
AfterOrder(node.Left);
AfterOrder(node.Right);
Console.Write(node);
}
}
public BinaryTree(string constructStr)
{
_strBinaryTree = constructStr;
_head = (string.IsNullOrEmpty(_strBinaryTree)) ? null : new BinaryTreeNode(_strBinaryTree[0]);
AddNode(_head, 0);
}
}