#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct node {
char data;
struct node *lchild;
struct node *rchild;
}BtNode;
void Create(BtNode *&b,char str[])
{
BtNode *St[2000], *p;
int top =0, k, j =0;
int end = 0;
char ch;
St[top] = b;
b->data = str[j];
j++;
int flag = 0;
while (str[j] != '\0')
{
if (flag==0)
{
if (str[j] != '#')
{
p = (BtNode *)malloc(sizeof(BtNode));
p->data = str[j];
p->lchild = NULL;
p->rchild = NULL;
St[top]->lchild = p;
end++;
St[end] = p;
flag = 1;
}
else
{
flag = 1;
}
}
else
{
if (str[j] != '#')
{
p = (BtNode *)malloc(sizeof(BtNode));
p->data = str[j];
p->lchild = NULL;
p->rchild = NULL;
St[top]->rchild = p;
top++;
end++;
St[end] = p;
flag = 0;
}
else
{
top++;
flag = 0;
}
}
j++;
}
}
void output(BtNode *b, int n)
{
if (b != NULL)
{
for (int i = 1; i <= (n-1)*4; i++)
{
printf(" ");
}
printf("%c\n", b->data);
output(b->lchild, n + 1);
output(b->rchild, n + 1);
}
}
void NLR(BtNode *b)
{
if (b != NULL)
{
printf("%c", b->data);
NLR(b->lchild);
NLR(b->rchild);
}
}
void LNR(BtNode *b)
{
if (b != NULL)
{
LNR(b->lchild);
printf("%c", b->data);
LNR(b->rchild);
}
}
void LRN(BtNode *b)
{
if (b != NULL)
{
;
LRN(b->lchild);
LRN(b->rchild);
printf("%c", b->data);
}
}
int Leaf(BtNode *b)
{
int num1, num2;
if (b == NULL)
{
return 0;
}
else if (b->lchild == NULL&&b->rchild == NULL)
{
return 1;
}
else
{
num1 = Leaf(b->lchild);
num2 = Leaf(b->rchild);
return (num1 + num2);
}
}
void Swap(BtNode *b,BtNode *&t)
{
if (b == NULL)
t = NULL;
else
{
t = (BtNode *)malloc(sizeof(BtNode));
t->data = b->data;
Swap(b->lchild, t->rchild);
Swap(b->rchild, t->lchild);
}
}
int main()
{
BtNode *b = (BtNode *)malloc(sizeof(BtNode));
char str[100];
gets_s(str);
b->lchild = b->rchild = NULL;
Create(b, str);
printf("BiTree\n");
output(b, 1);
printf("pre_sequence : ");
NLR(b);
printf("\n");
printf("in_sequence : ");
LNR(b);
printf("\n");
printf("post_sequence : ");
LRN(b);
printf("\n");
printf("Number of leaf: ");
printf("%d\n", Leaf(b));
BtNode *t;
t = (BtNode *)malloc(sizeof(BtNode));
Swap(b, t);
printf("BiTree swapped\n");
output(t, 1);
printf("pre_sequence : ");
NLR(t);
printf("\n");
printf("in_sequence : ");
LNR(t);
printf("\n");
printf("post_sequence : ");
LRN(t);
printf("\n");
int ssss = 1;
ssss = 2;
system("pause");
return 0;
}
二叉树
最新推荐文章于 2022-07-09 13:48:50 发布