P169 例8-3 编写程序,首先建立如图8-10(a)所示的不带头节点的二叉树,然后中序线索化二叉树,最后用循环结构输出该中序线索化二叉树各结点的序列信息。
头文件:InThreadIterator.h
#include<stdio.h>
#include<stdlib.h>
typedef char DataType;
typedef struct Node
{
DataType data;
int leftThread;
struct Node *leftChild;
struct Node *rightChild;
int rightThread;
}ThreadBiNode;
void InThread(ThreadBiNode *current,ThreadBiNode **pre)
{
if(current!=NULL)
{
InThread(current->leftChild,pre);
if(current->leftChild==NULL)
{
current->leftThread=1;
current->leftChild=*pre;
}
else
current->leftThread=0;
if(current->rightChild!=NULL)
current->rightThread=0;
else
current->rightThread=1;
if((*pre)->rightChild==NULL)
{
(*pre)->rightThread=1;
(*pre)->rightChild=current;
}
else
current->rightThread=0;
*pre=current;
InThread(current->rightChild,pre);
}
}
void CreatInThread(ThreadBiNode **root)
{
ThreadBiNode *t=*root;
ThreadBiNode *current,*pre=*root;
*root=(ThreadBiNode*)malloc(sizeof(ThreadBiNode));
if(t==NULL)
{
(*root)->leftThread=0;
(*root)->rightThread=1;
(*root)->leftChild=*root;
(*root)->rightChild=*root;
}
else
{
current=t;
(*root)->leftChild=t;
(*root)->leftThread=0;
InThread(current,&pre);
pre->rightChild=*root;
pre->rightThread=1;
(*root)->rightChild=pre;
(*root)->rightThread=1;
}
}
typedef struct
{
ThreadBiNode *root;
ThreadBiNode *current;
int nextComplete;
}ThreadBiTree;
void ThreadInitiate(ThreadBiTree *tree,ThreadBiNode *root)
{
tree->root=root;
tree->current=root;
if(root==NULL)
tree->nextComplete=1;
else
tree->nextComplete=0;
}
void First(ThreadBiTree *tree)
{
tree->current=tree->root;
while(tree->current->leftThread==0)
tree->current=tree->current->leftChild;
if(tree->current==tree->root)
tree->nextComplete=1;
else
tree->nextComplete=0;
}
void Next(ThreadBiTree *tree)
{
ThreadBiNode *p=tree->current->rightChild;
if(tree->nextComplete==1)
return;
if(tree->current->rightThread==0)
{
while(p->leftThread==0)
{
p=p->leftChild;
}
}
tree->current=p;
if(tree->current==tree->root)
tree->nextComplete=1;
}
int EndOfNext(ThreadBiTree *tree)
{
return tree->nextComplete;
}
ThreadBiNode *GetTreeNode(DataType item,ThreadBiNode *left,ThreadBiNode *right)
{
ThreadBiNode *p;
p=(ThreadBiNode *)malloc(sizeof(ThreadBiNode));
p->data=item;
p->leftChild=left;
p->rightChild=right;
return p;
}
void MakeCharTree(ThreadBiNode **root)
{
ThreadBiNode *b,*c,*d,*e,*f,*g;
g=GetTreeNode('G',NULL,NULL);
d=GetTreeNode('D',NULL,g);
b=GetTreeNode('B',d,NULL);
e=GetTreeNode('E',NULL,NULL);
f=GetTreeNode('F',NULL,NULL);
c=GetTreeNode('C',e,f);
*root=GetTreeNode('A',b,c);
}
源文件:例8-3.c
#include<stdio.h>
#include"InThreadIterator.h"
int main()
{
ThreadBiNode *root;
ThreadBiTree tree;
MakeCharTree(&root);
CreatInThread(&root);
printf("二叉树中序正向遍历序列为:");
ThreadInitiate(&tree,root);
for(First(&tree);!EndOfNext(&tree);Next(&tree))
printf("%c ",tree.current->data);
return 0;
}