繁体中文
设为首页
加入收藏
当前位置:.Net技术首页 >> C#语言 >> C#线索二叉树

C#线索二叉树

2004-10-01 08:26:10  作者:  来源:互联网  浏览次数:23  文字大小:【】【】【
简介:using System; namespace BiThrTree { /// <summary> /// 定义结点类: /// </summary> class BTNode { public char data; public int ltag,rtag;//0表示线索,1表示结点 public BTNode...
关键字:C# 线索

using System;

namespace BiThrTree

{

///

/// 定义结点类:

///

class BTNode

{

public char data;

public int ltag,rtag;//0表示线索,1表示结点

public BTNode lchild,rchild;

}

class BiThrTree

{

///

/// 建立一棵新二叉树:

///

///

static public void CreateBiThrTree(ref BTNode T)

{

char ch;

ch=(char)Console.Read();

if(ch=='#')

{

T=null;

}

else

{

T=new BTNode();

T.data=ch;

CreateBiThrTree(ref T.lchild);

CreateBiThrTree(ref T.rchild);

}

}

///

/// 线索化二叉树:

///

///

static BTNode pre,H;

static public void Threading(ref BTNode T)

{

H=pre=new BTNode();

pre.rchild=pre.lchild=null;

pre.rtag=pre.ltag=0;

Thread(ref T);

}

static public void Thread(ref BTNode T)

{

if(T!=null)

{

if(T.lchild==null){T.lchild=pre;T.ltag=0;}

else{T.ltag=1;}

if(T.rchild==null){T.rtag=0;}

else{T.rtag=1;}

if(pre.rchild==null&&pre.rtag==0)pre.rchild=T;

pre=T;

if(T.ltag==1)Thread(ref T.lchild);

if(T.rtag==1)Thread(ref T.rchild);

}

}

///

/// 先序输出:

///

static public void PrePrint(BTNode T)

{

if(T!=null)

{

Console.Write(T.data+"\t");

if(T.ltag==1)PrePrint(T.lchild);

if(T.rtag==1)PrePrint(T.rchild);

}

}

///

/// 先序线索遍历输出:

///

static public void PreThrPrint(BTNode T)

{

T=H.rchild;

//Console.WriteLine("H.rchild.date::"+H.rchild.data);

while(T!=null)

{

Console.Write(T.data+"\t");

if(T.rtag==0)T=T.rchild;

else{

if(T.ltag==1)T=T.lchild;

else{

T=T.rchild;

}

}

}

}

///

/// Deepth of a BiThrTree:

///

static public int Deepth(BTNode T)

{

int a,b;

if(T!=null)

{

if(T.ltag==1)a=Deepth(T.lchild);else a=0;

if(T.rtag==1)b=Deepth(T.rchild);else b=0;

return (1+max(a,b));

}

else

{

return 0;

}

}

static public int max(params int[] w)

{

int max;

max=w[0];

for(int i=0;i

if(max

return max;

}

///

/// 复制线索二叉树:

///

static public void DulplicateBiThrTree(BTNode T1,ref BTNode T2)

{

if(T1!=null)

{

T2=new BTNode();

T2.data=T1.data;

T2.ltag=T1.ltag;T2.rtag=T1.rtag;

if(T2.ltag==1)DulplicateBiThrTree(T1.lchild,ref T2.lchild);else T2.lchild=T1.lchild;

if(T2.rtag==1)DulplicateBiThrTree(T1.rchild,ref T2.rchild);else T2.rchild=T1.rchild;

}

}

static void Main()

{

BTNode mytree=null;

Console.WriteLine("Please input a tree(for example:abc##d##ed###):");

CreateBiThrTree(ref mytree);

Threading(ref mytree);

PrePrint(mytree);

Console.WriteLine("\n按先序输出:\n");

PreThrPrint(mytree);

Console.WriteLine("\n该树的深度为:{0}",Deepth(mytree));

BTNode mytree2=null;

Console.WriteLine("调用复制函数得到的新树为:");

DulplicateBiThrTree(mytree,ref mytree2);

PrePrint(mytree2);

Console.ReadLine();

Console.ReadLine();

}

}

}

责任编辑:admin
相关文章