欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言--二叉树创建与遍历

程序员文章站 2022-05-06 21:36:42
...

C语言--二叉树创建与遍历

#include"stdio.h"
#include"stdlib.h"
struct tree
{
	char data;
	struct tree *lchild;
	struct tree *rchild;
};
//创建二叉树,按照前序遍历方式输入
void createtree(struct tree **T)
{
	char c;
	scanf("%c", &c);
	if(' ' == c)
	{
		*T = NULL;
	}
	else
	{
		*T = (struct tree *)malloc(sizeof(struct tree));
		(*T)->data = c;
		createtree(&(*T)->lchild);
		createtree(&(*T)->rchild);
	}
}
void visit(char c, int level)
{
	printf("%c在第%d层\n", c, level);
}

//前序遍历二叉树
void traversebtree(struct tree *T, int level)
{
	if( T )
	{
		visit(T->data, level);
		traversebtree(T->lchild, level+1);
		traversebtree(T->rchild, level+1);
/*中序遍历	
		traversebtree(T->lchild, level+1);
		visit(T->data, level);
		traversebtree(T->rchild, level+1);
*/
/*后序遍历
		traversebtree(T->lchild, level+1);
		traversebtree(T->rchild, level+1);
		visit(T->data, level);
*/
	}
}
int main()
{
	struct tree *T;
	createtree(&T);
	traversebtree(T, 1);
	return 0;
}

C语言--二叉树创建与遍历

相关标签: 二叉树 c语言