C语言--二叉树创建与遍历
程序员文章站
2022-05-06 21:36:42
...
#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;
}
上一篇: 根据先序遍历和后续遍历重构二叉树
下一篇: 二叉树的储存与遍历