1. 程式人生 > 其它 >二叉樹層序建樹

二叉樹層序建樹

不放假不放假卷似你卷似你

二叉樹的層序建樹

#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);
}