C语言二叉树爱吃窝窝头2023-11-302023-11-30#include<stdio.h>#include<stdlib.h>//定义二叉链表节点的类型typedef struct bitnode { char data; struct bitnode* lchild, * rchild;}bitnode;//先建立二叉链表bitnode* creat() { bitnode* T; char ch; scanf("%c", &ch); if (ch == '.') return NULL; else { T = (bitnode*)malloc(sizeof(bitnode)); if (!T) exit(0); T->data = ch; //按照根左右的顺序建立 T->lchild = creat(); T->rchild = creat(); return T; }}//先序遍历void preorder(bitnode* T) { if (T) { printf("%c", T->data); //访问根 preorder(T->lchild); preorder(T->rchild); }}//中序遍历void inorder(bitnode* T) { if (T) { inorder(T->lchild); printf("%c", T->data); inorder(T->rchild); }}//后序遍历void postorder(bitnode* T) { if (T) { inorder(T->lchild); inorder(T->rchild); printf("%c", T->data); }}//子叶个数int leafsum(bitnode* T) { if (!T) //如果没有元素则没有叶子节点 return 0; else if (!T->rchild && !T->lchild) //如果都没有左孩子和右孩子返回1 return 1; else return leafsum(T->lchild) + leafsum(T->rchild); //若其他情况继续递归执行函数}//先序求结点个数int n=0;void count(bitnode *T){ if(T) { n++; count(T->lchild); count(T->rchild); }}//后序求二叉树的深度int depth(bitnode *T){ int h,l,r; if(!T) h=0; else { l=depth(T->lchild); r=depth(T->rchild); h=(l>r?l:r)+1; } return h;}void main() { bitnode* root; printf("请输入二叉树:"); root = creat(); printf("先序建立结果:"); preorder(root); printf("\n先序建立结果:"); inorder(root); printf("\n先序建立结果:"); postorder(root); printf("\n叶子结点的总数:"); printf("%d", leafsum(root)); count(root); printf("\n结点的个数为:%d",n); printf("\n树的深度为:%d",depth(root));}