初学数据结构自己写的二叉树,方便以后看

来源:互联网 发布:殊知的意思是什么 编辑:程序博客网 时间:2024/05/16 11:08
二叉树的创建和递归
#include<stdio.h>#include<stdlib.h>typedef struct Node{char data;struct Node *Lchild;struct Node *Rchild;}BiTree;BiTree *CreatBiTree(){char ch;BiTree *root;ch=getchar();if(ch=='#')root=NULL;else{root=(BiTree *)malloc(sizeof(BiTree));root->data=ch;    root->Lchild=CreatBiTree();root->Rchild=CreatBiTree();}return root;}void Visit(BiTree *root){if(root->data!='#'){printf("%c ",root->data);}}void PreOrder(BiTree *root){               //先序遍历if(root!=NULL){    Visit(root);PreOrder(root->Lchild);PreOrder(root->Rchild);}}void InOrder(BiTree *root){                //中序遍历if(root!=NULL){InOrder(root->Lchild);Visit(root);InOrder(root->Rchild);}}void PostOrder(BiTree *root){             //后序遍历if(root!=NULL){PostOrder(root->Lchild);PostOrder(root->Rchild);Visit(root);}}void main(){BiTree *CreatBiTree();    void PreOrder(BiTree *root);void InOrder(BiTree *root);void PostOrder(BiTree *root);void Visit(BiTree *root);BiTree *g;    g=CreatBiTree();printf("先序遍历的结果为:\n");PreOrder(g);printf("\n");printf("中序遍历的结果为:\n");InOrder(g);printf("\n");printf("后序遍历的结果为;\n");PostOrder(g);printf("\n");}

0 0