天天看点

C#实现二叉树遍历

using system ;

using system.collections.generic;

using system .text;

namespace structure

{

class program

class nodes<t>

t data;

nodes<t> lnode,rnode,pnode;

public t data

get {return data;}

set{data =value;}

}

public nodes<t>lnode

get {return lnode ;}

set {lnode =value;}

public nodes<t>rnode

get {return rnode ;}

set {rnode =value;}

public nodes<t>pnode

get {return pnode ;}

set {pnode =value;}

public nodes(){}

public nodes(t data)

this.data =data ;

//构造一棵已知的二叉树

static nodes<string>bintree()

nodes<string>[] bintree=new nodes<string>[8];

//创建节点

bintree [0]=new nodes<string> ("a");

bintree [1]=new nodes<string> ("b");

bintree [2]=new nodes<string> ("c");

bintree [3]=new nodes<string> ("d");

bintree [4]=new nodes<string> ("e");

bintree [5]=new nodes<string> ("f");

bintree [6]=new nodes<string> ("g");

bintree [7]=new nodes<string> ("h");

//使用层次遍历二叉树的思想,构造一个已知的二叉树

bintree [0].lnode=bintree [1];

bintree [0].rnode=bintree [2];

bintree [1].rnode =bintree [3];

bintree [2].lnode=bintree [4];

bintree [2].rnode=bintree [5];

bintree [3].lnode =bintree [6];

bintree[3].rnode=bintree [7];

//返回二叉树根节点

return bintree [0];

//先序遍历

static void preorder<t>(nodes<t> rootnode)

if(rootnode !=null )

console.writeline(rootnode.data);

preorder <t>(rootnode.lnode );

preorder <t>(rootnode.rnode);

//中序遍历二叉树

static void midorder<t>(nodes<t> rootnode)

if (rootnode != null)

midorder<t>(rootnode.lnode);

midorder<t>(rootnode.rnode);

//后序遍历二叉树

static void afterorder<t>(nodes<t> rootnode)

afterorder<t>(rootnode.lnode);

afterorder<t>(rootnode.rnode);

//层次遍历二叉树

static void layerorder<t>(nodes<t> rootnode)

nodes<t>[] nodes = new nodes<t>[20];

int front = -1;

int rear = -1;

rear++;

nodes[rear] = rootnode;

while (front != rear)

front++;

rootnode = nodes[front];

if (rootnode.lnode != null)

nodes[rear] = rootnode.lnode;

if (rootnode.rnode != null)

nodes[rear] = rootnode.rnode;

//测试的主方法

static void main(string[] args)

nodes<string> rootnode = bintree();

console.writeline("先序遍历方法遍历二叉树:");

preorder<string>(rootnode);

console.writeline("中序遍历方法遍历二叉树:");

midorder<string>(rootnode);

console.writeline("后序遍历方法遍历二叉树:");

afterorder<string>(rootnode);

console.writeline("层次遍历方法遍历二叉树:");

layerorder<string>(rootnode);

console.read();