1. 程式人生 > >二叉樹陣列表示法,連結串列表示法,中序遍歷

二叉樹陣列表示法,連結串列表示法,中序遍歷

/*
輸出結果:
[1]=5 [2]=2 [3]=9 [4]=1 [5]=4 [6]=7 [10]=3 [12]=6 [13]=8
1 2 3 4 5 6 7 8 9
*/
#include <stdio.h>
#include <malloc.h>

struct b_tree
{
	struct b_tree *left;	/*存放左子樹的指標*/
	int data;
	struct b_tree *right;	/*存放右子樹的指標*/ 
};
typedef struct b_tree *tree;

/*二叉樹連結串列表示法*/
tree creat_tree(tree root, int *input, int num)
{
	int i;
	tree newnode;
	tree current;
	tree parent;

	for (i=0; i<num; i++)
	{
		newnode = (tree)malloc(sizeof(struct b_tree));
		newnode->left = NULL;
		newnode->data =input[i];
		newnode->right = NULL;

		if (root == NULL)
		{
			root = newnode;
		}
		else
		{
			current = root;
			while(current != NULL)
			{	
				parent = current;
				if (newnode->data > current->data)
				{
					current = current->right;
				}
				else
				{
					current = current->left;
				}
			}

			if (newnode->data > parent->data)
			{
				parent->right = newnode;
			}
			else
			{
				parent->left = newnode;
			}
		}

	}
	return root;
}

/*中序遍歷*/
void mid_order(const tree root)
{
	tree p = root;
	if(p != NULL)
	{
		mid_order(p->left);		/*處理左子樹*/
		printf("%d ",p->data);
		mid_order(p->right);	/*處理右子樹*/
	}
}



/*二叉樹陣列表示*/
void attay_to_btree(int *input, int num, int* output)
{

	int level;
	int i;

	output[1] = input[0];
	for (i=1; i<num; i++)
	{
		level = 1;
		while(output[level] != 0)
		{
			if (input[i] < output[level])
			{
				level = 2 * level;
			}
			else
			{
				level = 2 * level + 1;
			}
		}
		output[level] = input[i];
	}
}

/*二叉樹陣列表示後輸出*/
void btree_print(const int *input, const int num)
{
	int i;
	for (i=0; i<num; i++)
	{
		if (input[i] != 0)
		{
			printf("[%d]=%d ", i, input[i]);
		}
	}
}


int main()
{
	int data1[]={5,2,9,1,4,7,3,6,8};
	int data2[1024]={0};
	tree root = NULL;

	/*二叉樹資料表示法*/
	attay_to_btree(data1, sizeof(data1)/sizeof(data1[0]), data2);
	btree_print(data2, sizeof(data2)/sizeof(data2[0]));
	printf("\n");

	/*二叉樹連結串列表示法*/
	root = creat_tree(root,data1,sizeof(data1)/sizeof(data1[0]));
	mid_order(root);
	printf("\n");
}