前序遍歷_中序遍歷_後序遍歷

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/**
 *本實例演示二叉樹的前序遍歷
 * **/
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() );
        }
    }
}

node

相關文章
相關標籤/搜索