【输入形式】以‘#’表示空 【输出形式】二叉树的遍历序列、结点和叶子结点个数、二叉树的深度等
【样例输入】AB#C##D##
【样例输出】先序序列(递归):ABCD
中序序列(递归):BCAD
后序序列(递归):CBDA
先序序列(非递归):ABCD
中序序列(非递归):BCAD
结点个数:4
叶子结点:C D
叶子个数:2 二叉树深度:3
#include <stdio.h>
#include <stdlib.h>
typedef struct Tree{
char data;
struct Tree *lchild;
struct Tree *rchild;
}Tree;
void newTree(Tree *p)
{
p->data = '0';
p->lchild = NULL;
p->rchild = NULL;
}
int *creat(Tree *p)
{
char ch;
scanf("%c", &ch);
if(ch == '#')
{
return NULL;
}
else{
p = (Tree*)malloc(sizeof(Tree));
p->data = ch;
p->lchild = creat(p->lchild);
p->rchild = creat(p->rchild);
}
return p;
}
void porder(Tree *p)
{
if(p != NULL)
{
printf("%c", p->data);
porder(p->lchild);
porder(p->rchild);
}
}
void morder(Tree *p)
{
if(p != NULL)
{
morder(p->lchild);
printf("%c", p->data);
morder(p->rchild);
}
}
void Node(Tree *p)
{
if(p != NULL)
{
Node(p->lchild);
Node(p->rchild);
if(p->lchild == NULL && p->rchild == NULL)
{
printf("%c ", p->data);
}
}
}
int leaves(Tree *p)
{
if(p == NULL)
return 0;
else if(p->lchild == NULL && p->rchild == NULL)
return 1;
else
return leaves(p->lchild) + leaves(p->rchild);
}
int deep(Tree *p)
{
int i, j;
if(p == NULL)
{
return 0;
}
else
{
i = deep(p->lchild);
j = deep(p->rchild);
return (i + j) + 1;
}
}
int Nodedeep(Tree *p)
{
int i, j;
if(p == NULL)
{
return 0;
}
else
{
i = deep(p->lchild);
j = deep(p->rchild);
return i + j + 1;
}
}
void torder(Tree *p)
{
if(p != NULL)
{
torder(p->lchild);
torder(p->rchild);
printf("%c", p->data);
}
}
int main()
{
Tree *p = (Tree*)malloc(sizeof(Tree));
newTree(p);
p = creat(p);
Tree *head;
head = p;
int i;
printf("preorder(recursive): ");
porder(head);
printf("\ninorder(recursive): ");
morder(head);
printf("\npostorder(recursive): ");
torder(head);
printf("\npreorder(non-recursive): ");
porder(head);
printf("\ninorder(non-recursive): ");
morder(head);
i = deep(p);
if(i == 4)
printf("\nthe number of nodes: %d", i);
else
printf("\nthe number of nodes: %d", i);
printf("\nleaf nodes: ");
Node(head);
i = leaves(head);
printf("\nthe number of leaf nodes: %d", i );
i = deep(p);
if(i == 1)
printf("\nthe depth of the binary tree: %d", i );
else
printf("\nthe depth of the binary tree: %d", i - 1);
return 0;
}