二叉树相关操作

来源:互联网 发布:手机文件夹加密软件 编辑:程序博客网 时间:2024/04/25 06:57
#include "stdio.h"#include "stdlib.h"#include "malloc.h"typedef struct Node/*类型定义*/{int data;Node * LChild;Node * RChild;}BiTree;BiTree * CreateBiTree(BiTree * bt)/*先序创建二叉树*/{char ch;    ch=getchar();if(ch=='.') {bt=NULL;}else{bt=(BiTree *)malloc(sizeof(BiTree));bt->data=ch;bt->LChild=CreateBiTree(bt->LChild);bt->RChild=CreateBiTree(bt->RChild);}return bt;}void PreOrder(BiTree * bt)/*先序遍历二叉树*/{if(bt){printf("%c",bt->data);PreOrder(bt->LChild);PreOrder(bt->RChild);}}void ZhongOrder(BiTree * bt)/*中序遍历二叉树*/{if(bt){PreOrder(bt->LChild);printf("%c",bt->data);PreOrder(bt->RChild);}}//统计叶子节点个数算法1int totalLeaf1(BiTree * bt){int sum=0,m,n;if(bt!=NULL){if(bt->LChild==NULL && bt->RChild==NULL)sum++;m=totalLeaf1(bt->LChild);sum+=m;n=totalLeaf1(bt->RChild);sum+=n;}return sum;}//统计叶子节点个数算法1int totalLeaf2(BiTree * bt){int sum;if(bt==NULL)sum = 0;else if(bt->LChild==NULL && bt->RChild==NULL)sum = 1;else{sum=totalLeaf2(bt->LChild)+totalLeaf2(bt->RChild);}return sum;}//树的深度int BtDepth(BiTree * bt){int depth,depthl,depthr;if(bt==NULL)depth=0;    else{depthl=BtDepth(bt->LChild);depthr=BtDepth(bt->RChild);depth=1+(depthl>depthr?depthl:depthr);}return depth;}//按树状打印void printTree(BiTree * bt,int depth){if(bt==NULL)return;printTree(bt->RChild,depth+1);//打印右子树for(int i=0;i<depth;i++)printf("  ");printf("%c\n",bt->data);printTree(bt->LChild,depth+1);//打印左子树}void main()/*主入口*/{BiTree * bt;    printf("创建二叉树:");  bt=CreateBiTree(bt);printf("先序遍历:");  PreOrder(bt);  printf("\n");printf("中序遍历:");  ZhongOrder(bt);  printf("\n");printf("树深度:%d\n",BtDepth(bt));printTree(bt,3);}/*#include "malloc.h"#include "stdio.h"#include "string.h"#define NULL 0  typedef struct BiTNode{          //类型定义  char data;  struct BiTNode *lchild,*rchild;  }BiTNode,*BiTree;  BiTree Create(BiTree T){         //创建char ch;ch=getchar();if(ch=='#')T=NULL;else{if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))printf("Error!");T->data=ch;T->lchild=Create(T->lchild);T->rchild=Create(T->rchild);}return T;}  void Preorder(BiTree T){        //先序遍历if(T){printf("%c",T->data);Preorder(T->lchild);Preorder(T->rchild);}}  int Sumleaf(BiTree T){          //叶子节点个数  int sum=0,m,n;  if(T){  if((!T->lchild)&&(!T->rchild))  sum++;  m=Sumleaf(T->lchild);  sum+=m;  n=Sumleaf(T->rchild);  sum+=n;  }  return sum;  }  void zhongxu(BiTree T){          //中序遍历if(T){zhongxu(T->lchild);printf("%c",T->data);zhongxu(T->rchild);}}void houxu(BiTree T){            //后序遍历if(T){houxu(T->lchild);houxu(T->rchild);printf("%c",T->data);}}  int Depth(BiTree T){             //树的深度  int dep=0,depl,depr;  if(!T) dep=0;  else{  depl=Depth(T->lchild);  depr=Depth(T->rchild);  dep=1+(depl>depr?depl:depr);  }  return dep;  }  main(){                           //主程序入口BiTree T;int sum,dep;T=Create(T);Preorder(T);printf("\n");zhongxu(T);printf("\n");houxu(T);printf("\n");sum=Sumleaf(T);printf("%d",sum);dep=Depth(T);printf("\n%d",dep);}*/

原创粉丝点击