using System;
namespace BiThrTree
{
/// <summary>
/// 定義結點類:
/// </summary>
class BTNode
{
public char data;
public int ltag,rtag;//0表示線索,1表示結點
public BTNode lchild,rchild;
}
class BiThrTree
{
/// <summary>
/// 建立一棵新二叉樹:
/// </summary>
/// <param name="T"></param>
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);
}
}
/// <summary>
/// 線索化二叉樹:
/// </summary>
/// <param name="T"></param>
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);
}
}
/// <summary>
/// 先序輸出:
/// </summary>
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);
}
}
/// <summary>
/// 先序線索遍歷輸出:
/// </summary>
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;
}
}
}
}