|
// Binary cue storage representation of a binary tree
#include <stdio.h>
#include <iostream.h>
#include <stdlib.h>
#define NULL 0
#define OVERFLOW -1
#define OK 1
#define ERROR 0
typedef enum PointerTag {Link = 0, Thread};
typedef char TElemType;
typedef char Status;
typedef struct BiThrNode {
TElemType data;
struct BiThrNode * lchild, * rchild;
PointerTag LTag, RTag;
} BiThrNode, * BiTree;
BiTree CreateBiTree ()
{
TElemType ch;
BiTree T;
scanf ("% c",&ch);
if (ch == '#')
T = NULL;
else {
T = (BiTree) malloc (sizeof (BiThrNode));
T-> data = ch;
T-> lchild = CreateBiTree (); // This is Zhongxu creation?
T-> rchild = CreateBiTree ();
}
return T;
}
void InThreading (BiTree p) {
if (p) {
BiTree pre = NULL;
pre-> LTag = Link;
pre-> RTag = Thread;
pre-> rchild = pre;
if (! p) pre-> lchild = pre;
else pre-> lchild = p;
InThreading (p-> lchild);
if (! p-> lchild) {p-> LTag = Thread; p-> lchild = pre;}
if (! pre-> rchild) {pre-> RTag = Thread; pre-> rchild = p;}
pre = p;
InThreading (p-> rchild);
}
}
Status InOrderThreading (BiTree&Thrt, BiTree T) {
// Middle order traverses the two-difference tree and clues the order, Thrt points to the head
Ranch
Thrt-> LTag = Link;
Thrt-> RTag = Thread;
Thrt-> rchild = Thrt;
if (! T) Thrt-> lchild = Thrt;
else {
BiTree pre;
Thrt-> lchild = T;
pre = Thrt;
InThreading (T);
pre-> rchild = Thrt; // The last node is cued
pre-> RTag = Thread;
Thrt-> rchild = pre;
}
return OK;
}
// traverse
Status InOrderTraverse (BiTree T, Status (* Visit) (TElemType e)) {
BiThrNode * p;
p = T-> lchild;
while (p! = T) {
while (p-> LTag == Link) p = p-> lchild;
if (! Visit (p-> data)) return ERROR;
while (p-> RTag == Thread&&p-> rchild! = T) {
p = p-> rchild;
Visit (p-> data);
}
p = p-> rchild;
}
return OK;
}
Status Visit (TElemType e) {
cout << e;
return e;
}
void main () {
BiTree Thrt, t;
if (! (Thrt = (BiTree) malloc (sizeof (BiThrNode)))) exit (OVERFLOW);
cout << "a";
t = CreateBiTree ();
// InOrderThreading (Thrt, t);
cout << "jdiue";
InOrderTraverse (t, Visit);
} |
|