#include
#include
#include<string.h>
typedef char DataType;
#define MaxSize 100
typedef struct BiNode
{
DataType data;
struct BiNode* lchild, * rchild;
} BiNode;
BiNode* root;
void PreOrder(BiNode* root)
{
if (root == NULL) return;
else {
printf("%c ", root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void InOrder(BiNode* root)
{
if (root == NULL) return;
else {
InOrder(root->lchild);
printf("%c ", root->data);
InOrder(root->rchild);
}
}
void PostOrder(BiNode* root)
{
if (root == NULL) return;
else {
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%c ", root->data);
}
}
void LevelOrder(BiNode* root)
{
BiNode* q = NULL, * Q[MaxSize];
int rear=-1;
int front = rear; /*初始化顺序队列*/
if (root == NULL) return; /*二叉树为空,算法结束*/
Q[++rear] = root;
while (front != rear)
{
q = Q[++front]; /*出队*/
printf("%c ", q->data); /*访问结点,为char型*/
if (q->lchild != NULL) Q[++rear] = q->lchild;
if (q->rchild != NULL) Q[++rear] = q->rchild;
}
printf("\n");
}
BiNode* CreatBiTree(BiNode * root)
{
char ch;
scanf_s("%c", &ch);
if (ch == '#') root = NULL;
else
{
root = (BiNode*)malloc(sizeof(BiNode));
root->data = ch;
root->lchild = CreatBiTree(root->lchild); /*递归建立左子树*/
root->rchild = CreatBiTree(root->rchild); /*递归建立右子树*/
}
return root;
}
void DestroyBiTree(BiNode* root)
{
if (root == NULL) return;
else {
DestroyBiTree(root->lchild);
DestroyBiTree(root->rchild);
free(root);
}
}
int Depth(BiNode* root)
{
if (root == NULL) {
return 0;
}
else {
if (Depth(root->lchild) > Depth(root->rchild)) return (Depth(root->lchild) + 1);
else return (Depth(root->rchild) + 1);
}
}
void PrintLeaves(BiNode* root)
{
BiNode* L = root;
if (L == NULL) return;
else
{
if (L->lchild == NULL && L->rchild == NULL)
printf("%c ", L->data);
else
{
PrintLeaves(L->lchild);
PrintLeaves(L->rchild);
}
}
}
int main()
{
printf("按先序遍历顺序输入:\n");
root=CreatBiTree(root);
printf("先序遍历:\n");
PreOrder(root);
printf("\n");
printf("中序遍历:\n");
InOrder(root);
printf("\n");
printf("后序遍历:\n");
PostOrder(root);
printf("\n");
printf("层序遍历:\n");
LevelOrder(root);
printf("二叉树深度为:%d\n",Depth(root));
printf("二叉树所有叶子结点为:\n");
PrintLeaves(root);
return 0;
}
之前调试好没问题,但现在突然又不行了,一直在读入输入,怎么回事啊
有没有可能你的输入序列有问题