C# 二叉树遍历
class Program
{
static void Main( string[ ] args )
{
BinarySearcharTree nums = new BinarySearcharTree( );
nums.Insert( 3 );
nums.Insert( 2 );
nums.Insert( 3 );
nums.Insert( 4 );
nums.Insert( 5 );
nums.Insert( 6 );
Console.WriteLine( "中序遍历" );
nums.InOrder( nums.root );
Console.WriteLine( );
Console.WriteLine( "前序遍历" );
nums.PreOrder( nums.root );
Console.WriteLine( );
Console.WriteLine( "后序遍历");
nums.PostOrder( nums.root );
}
public class Node
{
public int data;
public Node NodeLeft { get; set; }
public Node NodeRight { get; set; }
public void DisplayNode( )
{
Console.Write( data + " " );
}
}
public class BinarySearcharTree
{
public Node root;
public BinarySearcharTree( )
{
root = null;
}
/// <summary>
/// 插入节点
/// </summary>
/// <param name="i">要插入的结点值</param>
public void Insert( int i )
{
Node newNode = new Node( );
newNode.data = i;
if ( root == null )
{
root = newNode;
}
else
{
Node current = root;
Node parent;
while ( true )
{
parent = current;
if ( i < current.data )
{
current = current.NodeLeft;
if ( current == null )
{
parent.NodeLeft = newNode;
break;
}
}
else
{
current = current.NodeRight;
if ( current == null )
{
parent.NodeRight = newNode;
break;
}
}
}
}
}
/// <summary>
/// 中序遍历
/// </summary>
/// <param name="theRoot"></param>
public void InOrder( Node theRoot )
{
if ( !( theRoot == null ) )
{
InOrder( theRoot.NodeLeft );
theRoot.DisplayNode( );
InOrder( theRoot.NodeRight );
}
}
/// <summary>
/// 前序遍历
/// </summary>
/// <param name="theRoot"></param>
public void PreOrder( Node theRoot )
{
if ( !( theRoot == null ) )
{
theRoot.DisplayNode( );
PreOrder( theRoot.NodeLeft );
PreOrder( theRoot.NodeRight );
}
}
/// <summary>
/// 后序遍历
/// </summary>
/// <param name="theRoot"></param>
public void PostOrder( Node theRoot )
{
if ( !( theRoot == null ) )
{
PreOrder( theRoot.NodeLeft );
PreOrder( theRoot.NodeRight );
theRoot.DisplayNode( );
}
}
}
}