#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#define MAL (NODE*)malloc(sizeof(NODE))
typedef struct node
{
char data;
struct node*lchild;
struct node *rchild;
}NODE;
NODE *Create()//创建一个二叉树
{
NODE *p;
char ch;
ch = getchar();
if (ch == '0')
p = NULL;
else
{
p = MAL;
p->data = ch;
p->lchild = Create();
p->rchild = Create();
}
return p;
}
void Print(NODE *p)//先序输出二叉树
{
if (p != NULL)
{
printf("%c ", p->data);
Print(p->lchild);
Print(p->rchild);
}
}
void Levelorder(NODE*p)//按层遍历
{
NODE *quene[100];
int front=-1, rear=0;
if (p == NULL)
return;
quene[0] = p;
while (front != rear)
{
front++;
printf("%c ", quene[front]->data);
if (quene[front]->lchild != NULL)
quene[++rear] = quene[front]->lchild;
if (quene[front]->rchild != NULL)
quene[++rear] = quene[front]->rchild;
}
}
void spreorder(NODE *t)//非递归先序遍历
{
int top;
NODE * stack[20], *p;
top = 0;
p = t;
stack[0] = t;
while (top >= 0)
{
top--;
printf("%c ", p->data);
if (p->rchild != NULL)
{
stack[++top] = p->rchild;
}
if (p->lchild != NULL)
{
stack[++top] = p->lchild;
}
p = stack[top];
}
}
int leafNum = 0;
void TotalNum(NODE *p)//计算总节点数
{
if(p!=NULL)
{
leafNum++;
TotalNum(p->lchild);
TotalNum(p->rchild);
}
}
int Depth(NODE *p)//计算深度
{
int m, n;
if (p == NULL)
return 0;
else
{
m = Depth(p->lchild);
n = Depth(p->rchild);
if (m > n)
return m + 1;
else
return n + 1;
}
}
bool Search(NODE *p, char x)
{
if (p!=NULL&&p->data == x)
return true;
if (p->lchild != NULL)
return(Search(p->lchild, x));
if (p->rchild != NULL)
return(Search(p->rchild, x));
return false;
}
//abc00de0g00f000
int main(void)
{
NODE*p;
p = Create();
Print(p);
printf("\n树的深度为%d\n", Depth(p));
TotalNum(p);
printf("树的总节点个数为%d\n",leafNum);
printf("\n按层遍历:");
Levelorder(p);
printf("\n非递归先序遍历:");
spreorder(p);
if (Search(p, 'g'))
printf("\n存在 g ");
else
printf("\n不存在 g ");
system("pause");
}
二叉树的操作大多建立在递归的基础之上,所以需要稍微了解下递归!
二叉树的基本操作
最新推荐文章于 2018-04-29 16:17:25 发布