#include <stdio.h>
#include <stdlib.h>
typedef struct BiNode
{
char data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
void CreateTree(BiTree *T)//输入有技巧!!
{
char ch;
scanf("%c",&ch);
if(ch==' ')
*T=NULL;
else
{
*T=(BiTree)malloc(sizeof(BiNode));
(*T)->data=ch;
CreateTree(&(*T)->lchild);
CreateTree(&(*T)->rchild);
}
}
void PreDisplay(BiTree T)
{
if(T)
{
printf("%c",T->data);
PreDisplay(T->lchild);
PreDisplay(T->rchild);
}
}
void InDisplay(BiTree T)
{
if(T)
{
InDisplay(T->lchild);
printf("%c",T->data);
InDisplay(T->rchild);
}
}
void PostDisplay(BiTree T)
{
if(T)
{
PostDisplay(T->lchild);
PostDisplay(T->rchild);
printf("%c",T->data);
}
}
void Display(BiTree T)
{
if(T)
{
printf("%c",T->data);
if(T->lchild!=NULL||T->rchild!=NULL)
{
printf("(");
if(T->lchild!=NULL)
Display(T->lchild);
printf(",");
if(T->rchild!=NULL)
Display(T->rchild);
printf(")");
}
}
}
int NodeNum(BiTree T)
{
if(T==NULL) return 0;
else if(T->lchild==NULL&&T->rchild==NULL) return 1;
else return NodeNum(T->lchild)+NodeNum(T->rchild)+1;
}
int LeafNodeNum(BiTree T)
{
if(T==NULL) return 0;
else if(T->lchild==NULL&&T->rchild==NULL) return 1;
else return LeafNodeNum(T->lchild)+LeafNodeNum(T->rchild);
}
int DeepthTree(BiTree T)
{
if(T==NULL) return 0;
else if(DeepthTree(T->lchild)>DeepthTree(T->rchild))
return 1+DeepthTree(T->lchild);
else
return 1+DeepthTree(T->rchild);
}
BiTree FindNode(BiTree T,char e)
{
BiTree p;
if(T==NULL){
printf("tree empty!
");
return NULL;
}
else if(T->data==e)
return T;
else
{
p=FindNode(T->lchild,e);
if(p!=NULL)
return p;
else
return FindNode(T->rchild,e);
}
}
void Display2(BiTree T)
{
BiTree S[20],p;
int level[100][2],top=-1,n,i;
char e;
if(T)
{
top++;
S[top]=T;
level[top][0]=1;
level[top][1]=2;
while(top>-1)
{
p=S[top];
n=level[top][0];
switch(level[top][1])
{
case 0:
e='L';
break;
case 1:
e='R';
break;
case 2:
e='B';
break;
}
for(i=0;i<n;i++)
printf(" ");
printf("%c(%c)",p->data,e);
for(i=n+1;i<40;i+=2)
printf("--");
printf("
");
top--;
if(p->rchild!=NULL)
{
top++;
S[top]=p->rchild;
level[top][1]=1;
level[top][0]+=4;
}
if(p->lchild!=NULL)
{
top++;
S[top]=p->lchild;
level[top][1]=0;
level[top][0]+=4;
}
}
}
}
int main()
{
BiTree T;
printf("请按先序遍历依次输入二叉树:
");
CreateTree(&T);
printf("二叉树的先序遍历是:
");
PreDisplay(T);
printf("
");
printf("二叉树的中序遍历是:
");
InDisplay(T);
printf("
");
printf("二叉树的后序遍历是:
");
PostDisplay(T);
printf("
");
printf("二叉树的广义表输出:
");
Display(T);
printf("
");
printf("二叉树的凹形输出:
");
Display2(T);
printf("
");
printf("二叉树T是%s
",(T==NULL)?"empty tree":"no empty tree");
printf("二叉树T的节点个数=%d
",NodeNum(T));
printf("二叉树T的叶子节点个数=%d
",LeafNodeNum(T));
printf("二叉树T的深度=%d
",DeepthTree(T));
return 0;
}
大量参考了资料书的代码!对非线性的数据结构还是不熟悉!