二叉樹的二叉連結串列儲存結構構建以及先序遍歷
阿新 • • 發佈:2019-02-03
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR -1
typedef int TElemType, Status;
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild, *rchild;;
}BiTNode, *BiTree;
Status CreateBiTree(BiTree &T)
{
//按先序次序輸入二叉樹中的結點的值(一個字元), #表示空樹
//構造二叉連結串列表示的二叉樹T
char ch;
scanf("%c", &ch);
if (ch == '#')
{
T = NULL;
return OK;
}
else
{
T = (BiTree)malloc(sizeof(BiTNode));
T->data = ch;
CreateBiTree(T->lchild); //遞迴建立左子樹
CreateBiTree(T->rchild); //遞迴建立右子樹
}
}
Status PreOrderTraverse(BiTree T )
{
//先序遍歷二叉連結串列結構儲存的二叉樹T,每訪問到一個結點輸出其值
if (T != NULL)
{
printf("%c",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild); //交換這三條語句的順序可以實現先、中、後序遍歷
return OK;
}
return OK;
}
void main()
{
BiTree T;
CreateBiTree(T);
PreOrderTraverse(T );
return;
}