二叉树层序建树
不放假不放假卷似你卷似你
二叉树的层序建树
#include<stdio.h>
#include<stdlib.h>
#define N 10
typedef struct Node
{
char c;
struct Node* pleft;
struct Node* pright;
}node,*pnode;
pnode buildtree()
{
pnode root = NULL;
char c[N + 1] = "ABCDEFGHIJ";//应该建一个队列来构建二叉树,这里为了简单直接用的数组
pnode p[N + 1];
int i;
int count;//存放现在在插入的节点
for (i = 0; i < N; i++)
{
p[i] = (pnode)calloc(1,sizeof(node));
p[i]->c = c[i];
}
for (i = 0; i < N; i++)
{
if (root == NULL)//若树为空
{
root = p[0];
count = 0;
}
else
{
if (p[count]->pleft == NULL)
{
p[count]->pleft = p[i];
}
else if (p[count]->pright == NULL)
{
p[count]->pright = p[i];
count++;
}
}
}
return root;
}
void pre_order(pnode tree)
{
if (tree!=NULL)//节点不为空则继续,空了就结束S
{
printf("%c", tree->c);
pre_order(tree->pleft);
pre_order(tree->pright);
}
}
void mid_order(pnode tree)
{
if (tree != NULL)
{
pre_order(tree->pleft);
printf("%c", tree->c);
pre_order(tree->pright);
}
}
void lat_order(pnode tree)
{
if (tree != NULL)
{
pre_order(tree->pleft);
pre_order(tree->pright);
printf("%c", tree->c);
}
}
int main()
{
pnode a = buildtree();
pre_order(a);
}