二叉树在c语言中的重要性不需再说,而线索二叉树则是二叉树中比较重要的一个应用。
一般的二叉树存储模式,空链的数目非常多,线索二叉树则利用这些空链使其指向节点的前驱和后继,改善二叉树的遍历效率。这些被重新利用的空链也就是“线索”了。
中序遍历线索二叉树:
#include <stdio.h>
#include <stdlib.h>
#define FALSE 0 /* point is not thread */
#define TRUE 1 /* point is thread */
typedef struct threaded_tree *threaded_pointer;
typedef struct threaded_tree{
short int left_thread;
threaded_pointer left_child;
char data;
threaded_pointer right_child;
short int right_thread;
}threaded_tree;
threaded_pointer pre;
threaded_pointer createTp(threaded_pointer T){
/* create a binarytree */
char ch;
scanf("%c", &ch);
if(ch == '#')
return NULL;
T = (threaded_pointer)malloc(sizeof(threaded_tree));
T->data = ch;
T->left_thread = FALSE;
T->right_thread = FALSE;
T->left_child = createTp(T->left_child);
T->right_child = createTp(T->right_child);
return T;
}
void inorderthread(threaded_pointer *p, threaded_pointer T){
/* add a root node to tree and thread tree */
(*p) = (threaded_pointer)malloc(sizeof(threaded_tree));
(*p)->left_thread = FALSE;
(*p)->right_thread = FALSE;
(*p)->right_child = (*p);
if(!T){
(*p)->left_child = p;
}
else{
(*p)->left_child = T;
pre = (*p);
in_thread(T);
pre->right_thread = TRUE;
pre->right_child = (*p);
}
}
void in_thread(threaded_pointer T){
/* inorder thread tree */
if(T){
in_thread(T->left_child);
if(!T->left_child){
T->left_thread = TRUE;
T->left_child = pre;
}
if(!pre->right_child){
pre->right_thread = TRUE;
pre->right_child = T;
}
pre = T;
in_thread(T->right_child);
}
}
/* these two functions can be finded in the book : fundamentals of data structures in C */
threaded_pointer insucc(threaded_pointer tree){
/* find the inorder sucessor of tree in a threaded binary tree */
threaded_pointer temp;
temp = tree->right_child;
if(!tree->right_thread)
while(!temp->left_thread)
temp = temp->left_child;
return temp;
}
void tinorder(threaded_pointer tree){
/* traverse the threaded binary tree inorder */
threaded_pointer temp = tree;
for(;;){
temp = insucc(temp);
if(temp == tree)
break;
printf("%3c", temp->data);
}
printf("\n");
}
int main(){
threaded_pointer p, threadTree;
printf("input the binary tree (# == NULL):");
threadTree = createTp(threadTree);
inorderthread(&p, threadTree);
printf("the threaded binary tree: ");
tinorder(p);
return 0;
}
程序结果: