二叉树遍历
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 前序遍历_中序遍历_后序遍历
{
class Program
{
static void Main( string[ ] args )
{
BinaryTree bin = new BinaryTree( );
bin.Insert( 23 );
bin.Insert( 34 );
bin.Insert( 45 );
bin.PreOrder( bin.Head );
}
}
public class Node
{
public int data { get; set; }
public Node LeftNode { get; set; }
public Node RightNode { get; set; }
public void DisplayNode( )
{
Console.WriteLine( data + " " );
}
}
public class BinaryTree
{
public Node Head;
public BinaryTree( )
{
Head = null;
}
public void Insert( int i )
{
Node newNode = new Node( );
newNode.data = i;
if ( Head == null )
{
Head = newNode;
}
else
{
Node current = Head;
Node parent;
while ( true )
{
parent = current;
if(i < current.data)
{
if ( parent == null )
{
parent.LeftNode = newNode;
break;
}
}
else
{
current = current.RightNode;
if ( parent == null )
{
parent.RightNode= newNode;
break;
}
}
}
}
}
/// <summary>
/// 中序遍历
/// </summary>
/// <param name="theRoot"></param>
public void InOrder( Node theRoot )
{
if ( !( theRoot == null ) )
{
InOrder( theRoot.LeftNode );
theRoot.DisplayNode( );
InOrder( theRoot.RightNode );
}
}
/// <summary>
/// 前序遍历
/// </summary>
/// <param name="theRoot"></param>
public void PreOrder( Node theRoot )
{
if ( !( theRoot == null ) )
{
theRoot.DisplayNode( );
PreOrder( theRoot.LeftNode );
PreOrder( theRoot.RightNode );
}
}
/// <summary>
/// 后序遍历
/// </summary>
/// <param name="theRoot"></param>
public void PosOrder( Node theRoot )
{
if ( !( theRoot == null ) )
{
PreOrder( theRoot.LeftNode );
PreOrder( theRoot.RightNode );
theRoot.DisplayNode( );
}
}
}
}