using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/**
*本实例演示hashu.html" target="_blank">二叉树的前序遍历
* **/
namespace 前序遍历
{
class Program
{
static void Main( string[ ] args )
{
BinaryTree b = new BinaryTree( "ABCDE#F" );
b.ProOrder( b.Head );
Console.WriteLine( );
b.MidPrder( b.Head );
Console.WriteLine( );
b.AfterPrder( b.Head );
Console.WriteLine( );
}
}
public class Node
{
public int NodeValue { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node( int nodeValue )
{
NodeValue = nodeValue;
}
public override string ToString( )
{
return NodeValue.ToString( );
}
}
public class BinaryTree
{
public Node Head { get; set; }
private string satr;
public BinaryTree( string currentNode )
{
satr = currentNode;
Head = new Node( satr[ 0 ] );
Add( Head, 0 );
}
private void Add( Node parcnt, int index )
{
int leftIndex = 2 * index + 1;
if ( leftIndex < satr.Length )
{
if ( satr[ leftIndex ] != '#' )
{
parcnt.Left = new Node( satr[ leftIndex ] );
Add( parcnt.Left, leftIndex );
}
}
int rightIndex = 2 * index + 2;
if ( rightIndex < satr.Length )
{
if ( satr[ rightIndex ] != '#' )
{
parcnt.Right = new Node( satr[ rightIndex ] );
Add( parcnt.Right, rightIndex );
}
}
}
/// <summary>
/// 先序遍历
/// </summary>
/// <param name="node"></param>
public void ProOrder( Node node )
{
if ( node !=null )
{
Console.Write(node.ToString() );
ProOrder( node.Left );
ProOrder( node.Right );
}
}
/// <summary>
///中序遍历
/// </summary>
/// <param name="node"></param>
public void MidPrder( Node node )
{
if ( node != null )
{
ProOrder( node.Left );
Console.Write(node.ToString() );
ProOrder( node.Right );
}
}
/// <summary>
///后序遍历
/// </summary>
/// <param name="node"></param>
public void AfterPrder( Node node )
{
ProOrder( node.Left );
ProOrder( node.Right );
Console.Write(node.ToString() );
}
}
}