二叉树的建立与递归遍历C语言版

</pre><pre name="code" class="cpp">#include <stdio.h>
#include <malloc.h> typedef struct BTNode
{
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode; void createTree(BTNode* *T)
{
char ch = getchar();
if(ch=='#')
{
*T=NULL;
return;
}
(*T) = (BTNode*)malloc(sizeof(BTNode));
(*T)->data = ch;
createTree(&(*T)->lchild);
createTree(&(*T)->rchild);
} void preOrder(BTNode *T)//先序遍历
{
if(T==NULL) return;
printf("%c\t", T->data);
if(T->lchild!=NULL)
preOrder(T->lchild);
if(T->rchild != NULL)
preOrder(T->rchild);
} void inOrder(BTNode *T)//中序遍历
{
if(T==NULL) return; if(T->lchild!=NULL)
inOrder(T->lchild);
printf("%c\t", T->data);
if(T->rchild != NULL)
inOrder(T->rchild);
} void postOrder(BTNode *T)//后序遍历
{
if(T==NULL) return; if(T->lchild!=NULL)
postOrder(T->lchild);
if(T->rchild != NULL)
postOrder(T->rchild);
printf("%c\t", T->data);
} int main(int argc, char const *argv[])
{
BTNode *T;
createTree(&T);
puts("PreOrder visit:");
preOrder(T);
putchar('\n'); puts("inOrder visit:");
inOrder(T);
putchar('\n'); puts("PostOrder visit:");
postOrder(T);
putchar('\n');
return 0;
}
/*运行结果: ABD###C##
PreOrder visit:
A B D C
inOrder visit:
D B A C
PostOrder visit:
D B C A
请按任意键继续. . .*/
上一篇:django进阶-查询(适合GET4以上人群阅读)


下一篇:css3中的多列布局columns详解