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

tech2022-07-14  179

#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; }

最新回复(0)