C语言笔试题(16)——二叉树基本算法
2012-09-09 09:50
417 查看
#include <stdio.h> #include <stdlib.h> struct node { char data; struct node *lchild, *rchild; }; //根据前序遍历创建二叉树('.'代表为空的结点) //输入124...35...验证 struct node *create_tree(void) { struct node *root; char x; x = getchar(); if (x == '.') root = NULL; else { root = (struct node *)malloc(sizeof(struct node)); root->data = x; root->lchild = create_tree(); root->rchild = create_tree(); } return root; } //前序遍历 void print_pre(struct node *root) { if (root == NULL) return ; else { printf("%c ", root->data); print_pre(root->lchild); print_pre(root->rchild); } return; } //中序遍历 void print_in(struct node *root) { if (root == NULL) return ; else { print_in(root->lchild); printf("%c ", root->data); print_in(root->rchild); } return; } //后序遍历 void print_post(struct node *root) { if (root == NULL) return ; else { print_post(root->lchild); print_post(root->rchild); printf("%c ", root->data); } return ; } //统计叶子节点 int countleaf(struct node *root) { int num = 0; if (root != NULL) { if (root->lchild == NULL && root->rchild == NULL) return 1; else return (countleaf(root->lchild) + countleaf(root->rchild)); } } //计算二叉树的深度 int treedepth(struct node *root) { int h, lh, rh; if (root == NULL) h = 0; else { lh = treedepth(root->lchild); rh = treedepth(root->rchild); if (lh >= rh) h = lh + 1; else h = rh + 1; } return h; } //统计度为1的结点 int count1(struct node *root) { int num = 0; if (root != NULL) { if (root->lchild != NULL && root->rchild != NULL) num = (count1(root->lchild) + count1(root->rchild) ); if ((root->lchild == NULL && root->rchild != NULL) || (root->lchild != NULL && root->rchild == NULL)) num = (count1(root->lchild) + count1(root->rchild) + 1); return num; } } int main(int argc, const char *argv[]) { struct node *root; struct node *p; root = create_tree(); print_pre(root); printf("\n"); print_in(root); printf("\n"); print_post(root); printf("\n"); printf("count : %d\n", countleaf(root)); printf("depth: %d\n", treedepth(root)); printf("count1 : %d\n", count1(root)); return 0; }
相关文章推荐
- C语言基本数据结构之二(二叉树的三种遍历,节点数以及深度算法)
- 笔试算法题(16):二叉树深度计算 & 字符串全排列
- 算法与数据结构-二叉树的基本操作C语言实现
- C语言之基本算法16—条件全排列
- 实现二叉树各种基本运算的算法
- C语言之基本算法06—斐波那契数列求和
- C语言之基本算法11—牛顿迭代法求平方根
- C语言之基本算法20—同构数
- 一个应用二叉树基本算法的程序
- C语言之基本算法31—杨辉三角
- C语言的一些基本算法
- C语言之基本算法35—数组上三角之积 主对角之积 副对角之积
- 数据结构——c语言描述 第六章(1)二叉树树的基本操作和二叉树的线索化
- C语言之基本算法39—字符串经典操作
- C语言-二叉树基本操作以及二叉搜索树基本操作
- C语言之基本算法33—矩阵的基本运算
- 【算法】二叉树的递归遍历C语言实现
- 打印菜单界面,用c语言实现二叉树的基本操作
- C语言之基本算法07—分子分母数列前30项和
- C语言之基本算法12—谁是冠军