/* ============== Program Description ============= */
/* Freshare’s 4th of dswork */
/* ================================================== */
#include "stdlib.h"
#include "stdio.h"
#define DataType char
#define Status int
#define ERROR -1
#define OK 1
#define MAX 255
typedef struct BiTNode //定义类型
{
DataType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree que[MAX],Tree,t;
int front=0, rear=0; //队列变量
BiTree CreateBiTree(BiTree T) //CreatBiTree
{
char ch;
ch=getchar();
if(ch==’ ’) T=NULL;
else{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
exit(ERROR);
T->data=ch;
T->lchild=CreateBiTree(T->lchild);
T->rchild=CreateBiTree(T->rchild);
}
return T;
}
void preorder(BiTree root)
{
if (root!=NULL)
{
printf("%c",root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}
void inorder(BiTree root)
{
if (root!=NULL)
{
inorder(root->lchild);
printf("%c",root->data);
inorder(root->rchild);
}
}
void postorder(BiTree root)
{
if (root!=NULL)
{
postorder(root->lchild);
postorder(root->rchild);
printf("%c",root->data);
}
}
void enqueue(BiTree t) //进队
{ if(front!=(rear+1) % MAX)
{ rear = (rear+1) % MAX;
que[rear]=t;
}
}
BiTNode *delqueue()
{ if (front==rear) return NULL;
front=(front+1) % MAX;
return (que[front]);
}
void levelorder(BiTree t)
{ BiTree p;
if(t!=NULL)
{
enqueue(t);
while(front!=rear)
{
p=delqueue( );
printf("%c", p->data);
if(p->lchild!=NULL) enqueue(p->lchild);
if(p->rchild!=NULL) enqueue(p->rchild);
}
}
}
BiTree findnode(BiTree t ,DataType x)
{
BiTree p;
if(!t) p=NULL;
else if(t->data==x) p=t;
else
{
p=findnode(t->lchild,x);
if(!p) p=findnode(t->rchild,x);
}
return (p);
}
BiTree findparent (BiTree root ,BiTree q)
{
BiTree p;
if(!root) return (NULL);
else if (root->lchild==q||root->rchild==q)
return (root);
else
{
p=findparent(root->lchild,q);
if(!p)p=findparent(root->rchild,q);
return (p);
}
}
int counter(BiTree root)
{
int s;
if(root==NULL) return (0);
else s=counter(root->lchild)+counter(root->rchild)+1;
return (s);
}
int depth(BiTree t)
{
int dep1,dep2;
if (t==NULL) return (0);
else
{
dep1=depth(t->lchild);
dep2=depth(t->rchild);
if (dep1>dep2) return (dep1+1);
else return (dep2+1);
}
}
void main()
{
char treen;
BiTree tmp;
Tree=CreateBiTree(Tree);
printf("该二叉树总结点数为:%d,高度为:%d/n前序遍历:",counter(Tree),depth(Tree));
preorder(Tree);
printf("/n中序遍历:");
inorder(Tree);
printf("/n后序遍历:");
postorder(Tree);
printf("/n层序遍历:");
levelorder(Tree);
printf("/n请输入一个节点:");
getchar();getchar();
treen=getchar();
tmp=findnode(Tree,treen);
printf("它的父结点是:%c/n/n",findparent(Tree,tmp)->data);
}
[数据结构]第四次作业:二叉数的各种算法
最新推荐文章于 2024-06-29 19:05:30 发布