您的位置:首页 > 其它

软基作业:二叉树的创建与遍历

2013-10-30 14:11 246 查看
题目要求:

ex4_1:

1)二叉树结点类型定义为:
typedefstructbnode
{  intdata;
   structbnode*lc,*rc;
}bnode_type;
2)编写中序遍历函数;
3)编写后序遍历函数;
4)编写先序遍历函数;
5)编写create函数建立二叉排序树;
6)编写main()函数,先调用create函数,建立一颗二叉排序树;然后分别调用中序、后序、先序遍历函数,将二叉树的先序、中序和后序遍历序列输出到屏幕上。


程序如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct bnode
{
	int data;
	struct bnode *lc, *rc;
}bnode_type;

bnode_type *create(void);
void preorder(bnode_type *root);
void inorder(bnode_type *root);
void postorder(bnode_type *root);

int main(void)
{
	bnode_type *tree;

	printf("Please input your datas(ended by -1):");
	tree = create();

	printf("Preorder:\n");
	preorder(tree);

	printf("\nInorder:\n");
	inorder(tree);

	printf("\nPostorder:\n");
	postorder(tree);
	printf("\n");

	return 0;
}

bnode_type *create(void)
{
	int data;
	bnode_type *node, *root, *newnode;
	
	root = (bnode_type *)malloc(sizeof(bnode_type));
	if (root ==	NULL)
	{
		printf("Memorty Error!\n");
		exit(EXIT_FAILURE);
	}

	root->data = -1;
	root->lc = root->rc = NULL;
	scanf("%d", &data);

	while (data != -1)
	{
		if (root->data == -1)
		{
			root->data = data;
			scanf("%d", &data);
			continue;
		}
		else
		{
			node = root;
			for (;;)
			{
				if (data < node->data)
				{
					if (node->lc == NULL)
					{
						newnode = (bnode_type *)malloc(sizeof(bnode_type));
						if (newnode == NULL)
						{
							printf("Memory Error!\n");
							exit(EXIT_FAILURE);
						}
						newnode->data = data;
						newnode->lc = newnode->rc = NULL;
						node->lc = newnode;
						break;
					}
					else
						node = node->lc;
				}
				else
				{
					if (node->rc == NULL)
					{
						newnode = (bnode_type *)malloc(sizeof(bnode_type));
						if (newnode == NULL)
						{
							printf("Memory Error!\n");
							exit(EXIT_FAILURE);
						}
						newnode->data = data;
						newnode->lc = newnode->rc = NULL;
						node->rc = newnode;
						break;
					}
					else
						node = node->rc;
				}
			}
		}
		scanf("%d", &data);
	}

	return root;
}

void preorder(bnode_type *root)
{
	if (root == NULL || root->data == -1)
		return ;

	printf("%d\t", root->data);
	if (root->lc != NULL)
		preorder(root->lc);
	if (root->rc != NULL)
		preorder(root->rc);
}

void inorder(bnode_type *root)
{
	if (root == NULL || root->data == -1)
		return ;

	if (root->lc != NULL)
		inorder(root->lc);
	printf("%d\t", root->data);
	if (root->rc != NULL)
		inorder(root->rc);
}

void postorder(bnode_type *root)
{
	if (root == NULL || root->data == -1)
		return ;

	if (root->lc != NULL)
		postorder(root->lc);
	if (root->rc != NULL)
		postorder(root->rc);
	printf("%d\t", root->data);
}


运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: