二叉树遍历:先序、中序、后序和层次遍历

public class BinaryNode
    
{
        
public int Data;
        
public BinaryNode Left;
        
public BinaryNode Right;
    }



public class BinaryTree
    
{
        
public void PreOrder(BinaryNode node)
        
{
            
if (node != null)
            
{
                Console.WriteLine(node.Data);

                PreOrder(node.Left);
                PreOrder(node.Right);
            }

        }


        
public void MidOrder(BinaryNode node)
        
{
            
if (node != null)
            
{
                MidOrder(node.Left);
                Console.WriteLine(node.Data);
                MidOrder(node.Right);
            }

        }


        
public void AfterOrder(BinaryNode node)
        
{
            
if (node != null)
            
{
                AfterOrder(node.Left);
                AfterOrder(node.Right);
                Console.WriteLine(node.Data);
            }

        }


        
public void LayerOrder(BinaryNode node)
        
{
            
if (node != null)
            
{
                CurrentLayer(node.Left);
                CurrentLayer(node.Right);

                LayerOrder(node.Left);
                LayerOrder(node.Right);
            }

        }


        
private void CurrentLayer(BinaryNode node)
        
{
            
if (node != null)
            
{
                Console.WriteLine(node.Data);
            }

        }


    }


测试:
            BinaryNode n1 = new BinaryNode();
            n1.Data 
= 27;

            BinaryNode n2 
= new BinaryNode();
            n2.Data 
= 83;

            BinaryNode n3 
= new BinaryNode();
            n3.Data 
= 123;

            BinaryNode n4 
= new BinaryNode();
            n4.Data 
= 98;

            BinaryNode n5 
= new BinaryNode();
            n5.Data 
= 94;

            BinaryNode n6 
= new BinaryNode();
            n6.Data 
= 48;

            BinaryNode n7 
= new BinaryNode();
            n7.Data 
= 61;

            n1.Left 
= n2;
            n1.Right 
= n3;
            n1.Left.Left 
= n4;
            n1.Left.Right 
= n5;
            n1.Right.Right 
= n6;
            n1.Right.Right.Left 
= n7;

            BinaryTree bTree 
= new BinaryTree();

            Console.WriteLine(
"Pre Order Binary Tree:");
            bTree.PreOrder(n1);

            Console.WriteLine(
"Midd Order Binary Tree:");
            bTree.MidOrder(n1);

            Console.WriteLine(
"After Order Binary Tree:");
            bTree.AfterOrder(n1);

            Console.WriteLine(
"Layer Order Binary Tree:");
            bTree.LayerOrder(n1);

            Console.ReadLine();

posted @ 2008-03-05 14:09  Ready!  阅读(502)  评论(0编辑  收藏  举报