在小数据测试的时候输出是正确的,但有些数据可能过不了。分别以DLR,LDR,LRD遍历二叉树,同时输出叶子节点以及树的深度。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10010
int LeafCount;
char s[MAX];
int pos;
typedef struct Node
{
char ch;
struct Node *LChild;
struct Node *RChild;
}BitNode,*BitTree;
void CreateBiTree(BitTree *tree)
{
if(s[pos]=='$' || s[pos]=='\0')
{
(*tree)=NULL;
pos++;
}
else
{
(*tree)=(BitNode *)malloc(sizeof(BitNode));
if((*tree)!=NULL)
{
(*tree)->ch=s[pos];
pos++;
CreateBiTree(&((*tree)->LChild));
CreateBiTree(&((*tree)->RChild));
}
}
}
void Traverse_1(BitTree tree)
{
if(tree!=NULL)
{
printf("%c",tree->ch);
if(tree->LChild==NULL && tree->RChild==NULL)
{
LeafCount+=1;
}
Traverse_1(tree->LChild);
Traverse_1(tree->RChild);
}
}
void Traverse_2(BitTree tree)
{
if(tree!=NULL)
{
Traverse_2(tree->LChild);
printf("%c",tree->ch);
Traverse_2(tree->RChild);
}
}
void Traverse_3(BitTree tree)
{
if(tree!=NULL)
{
Traverse_3(tree->LChild);
Traverse_3(tree->RChild);
printf("%c",tree->ch);
}
}
int GetDepth(BitTree tree)
{
int lh,rh,max;
if(tree!=NULL)
{
lh=GetDepth(tree->LChild);
rh=GetDepth(tree->RChild);
max=lh>rh?lh:rh;
return (max+1);
}
else
return 0;
}
void DeleteTree(BitTree tree)
/* 释放双亲节点之前要先释放孩子节点 */
{
if(tree==NULL)
{
return;
}
DeleteTree(tree->LChild);
DeleteTree(tree->RChild);
free(tree);
}
int main()
{
BitTree bt;
int depth;
while(scanf("%s",s)!=EOF)
{
pos=0;
if(strlen(s)==0)
continue;
if(1==strlen(s) && s[pos]=='$')
{
printf("0\n0\n\n");
}
else
{
LeafCount=0;
CreateBiTree(&bt);
Traverse_1(bt);
printf("\n");
Traverse_2(bt);
printf("\n");
Traverse_3(bt);
printf("\n");
depth=GetDepth(bt);
printf("%d\n",depth);
printf("%d\n",LeafCount);
DeleteTree(bt);
printf("\n");
}
}
return 0;
}