您的位置:首页 > 其它

软基作业——先序遍历法生成二叉树

2013-10-30 17:23 218 查看
题目为:



程序如下:

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

typedef struct bnode_type
{
	char data;
	struct bnode_type *leftchild;
	struct bnode_type *rightchild;
}bnodetype;

void input(bnodetype **root);
bool memorytest(bnodetype *node); 
void preorder(bnodetype *root);

int main(void)
{
	bnodetype *root;
	root= NULL;

	input(&root);
	printf("The tree is\n");
	preorder(root);
	printf("\n");

	return 0;
}

bool memorytest(bnodetype *node)
{
	if (node == NULL)
		exit(EXIT_FAILURE);
	return true;
}

void input(bnodetype **root)
{
	char data;

	if (*root == NULL)
	{
		data = getchar();
		if (data == ' ' || data == '\n')
			return ;

		*root = (bnodetype *)malloc(sizeof(bnodetype));
		memorytest(*root);
		(*root)->data = data;
		(*root)->leftchild = NULL;
		(*root)->rightchild = NULL;
	}
	if ((*root)->leftchild == NULL)
		input(&(*root)->leftchild);
	if ((*root)->rightchild == NULL)
		input(&(*root)->rightchild);
}

void preorder(bnodetype *root)
{
	if (root != NULL)
	{
		printf("%c", root->data);
		preorder(root->leftchild);
		preorder(root->rightchild);
	}
}


运行效果如下:

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