层次遍历:
#include<stdio.h>
typedef struct tagtree{
char ch;
struct tagtree *lchild,*rchild;
}tree;
#define MAX 100
tree* a[MAX]; //队列
static int front,tail;
front=0; tail=0;
void push(tree* t) //入对
{
if( (tail+1)%MAX==front ) { printf("queue error: push()\n"); exit(1); }
a[tail]=t;
tail=(tail+1)%MAX;
}
tree* pop() //出对
{
tree* r;
if(front==tail) { printf("queue error: pop()\n"); exit(1); }
r=a[front]; front=(front+1)%MAX;
return r;
}
int empty() //队空?
{ return front==tail; }
void visit(tree *root) //层次遍历
{
tree *t;
if(root) push(root);
while(!empty())
{
t=pop();
printf("%c",t->ch);
if(t->lchild) push(t->lchild);
if(t->rchild) push(t->rchild);
}
}
void CreateBinTree(tree **T) //建树 引用别人的:)
{
char ch;
flushall();
if( (ch=getchar())==' ' )
*T=NULL;
else
{
*T=(tree *)malloc(sizeof(tree*));
(*T)->ch=ch;
printf("%c left:",ch); CreateBinTree(&(*T)->lchild);
printf("%c right:",ch); CreateBinTree(&(*T)->rchild);
}
}
void main()
{ tree *root;
CreateBinTree(&root);
visit(root);
return;
}
////////////////////////////////////////////////////////////////////
对二叉树中序穿线
#include<stdio.h>
typedef struct tagtree{
char ch;
int lflag,rflag;
struct tagtree *lchild,*rchild;
}tree;
void thread(tree *root, tree **h)//对二叉树中序穿线
{
if(root)
{
thread(root->lchild,h); //左子树穿线
if(*h && root->lchild==NULL) //h是root的前结点
{ root->lchild=*h; root->lflag=1; }
if( (*h) && (*h)->rchild==NULL ) //root是h的后结点
{ (*h)->rchild=root; (*h)->rflag=1; }
*h=root; //右子树穿线
thread(root->rchild,h);
}
}
void CreateBinTree(tree **T) //前序建树
{
char ch;
flushall();
if( (ch=getchar())==' ' )
*T=NULL;
else
{
*T=(tree *)malloc(sizeof(tree*));
(*T)->ch=ch; (*T)->lflag=(*T)->rflag=0;
printf("%c left:",ch); CreateBinTree(&(*T)->lchild);
printf("%c right:",ch); CreateBinTree(&(*T)->rchild);
}
}
void visit(tree *root) //前序遍历穿线树。(穿线树有非递归遍历方式)
{
if(root)
{
printf("(%d,%c,%d),",root->lflag,root->ch,root->rflag);
if(root->lflag==0) visit(root->lchild);
if(root->rflag==0) visit(root->rchild);
}
}
void main()
{ tree *root, *h=NULL;
CreateBinTree(&root);
thread(root,&h);
visit(root);
return;
}