本题要求给定二叉树的4种遍历。
函数接口定义:
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );
其中BinTree
结构定义如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
要求4个函数分别按照访问顺序打印出结点的内容,格式为一个空格跟着一个字符。
实现:
void InorderTraversal( BinTree BT )
{
if (BT == NULL)
return ;
InorderTraversal(BT->Left);
printf(" %c", BT->Data);
InorderTraversal(BT->Right);
}
void PreorderTraversal( BinTree BT )
{
if (BT == NULL)
return ;
printf(" %c", BT->Data);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
void PostorderTraversal( BinTree BT )
{
if (BT == NULL)
return ;
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
printf(" %c", BT->Data);
}
void LevelorderTraversal( BinTree BT )
{
BinTree *que;
int head = 0, tail = 0;
if (BT == NULL)
return ;
que = (BinTree *)malloc(sizeof(struct TNode) * 100);
que[tail++] = BT;
while (head != tail) {
BinTree now = que[head++];
printf(" %c", now->Data);
if (now->Left != NULL)
que[tail++] = now->Left;
if (now->Right != NULL)
que[tail++] = now->Right;
}
free(que);
}