二叉树的二叉链表表示与实现
来源:互联网 发布:用支付宝找回淘宝密码 编辑:程序博客网 时间:2024/09/21 08:49
二叉树的存储结构可以用顺序存储和链式存储来存储。二叉树的顺序存储结构由一组连续的存储单元依次从上到下,从左到右存储完全二叉树的结点元素。对于一般二叉树,应将其与完全二叉树对应,然后给每个结点从1到i编上号,依次存储在大小为i-1的数组中。这种方法只适用于完全二叉树,对非完全二叉树会浪费较多空间,最坏情况一个深度为k的二叉树只有k个结点,却需要长度为2的k次方减一长度的一位数组。事实上,二叉树一般使用链式存储结构,由二叉树的定义可知,二叉树的结点由一个数据元素和分别指向其左右孩子的指针构成,即二叉树的链表结点中包含3个域,这种结点结构的二叉树存储结构称之为二叉链表。
- 二叉链表的存储结构
- typedef struct tnode {
- elemtype data;
- struct tnode *lchild;
- struct tnode *rchild;
- }*bitree, bitnode;
- 创建一棵二叉树(按先序序列建立)
- int create_bitree(bitree *bt)
- {
- elemtype data;
- scanf("%d", &data);
- if (0 == data) {
- *bt = NULL;
- } else {
- *bt = (bitree)malloc(sizeof(bitnode));
- if (!(*bt))
- exit(OVERFLOW);
- (*bt)->data = data;
- create_bitree(&(*bt)->lchild);
- create_bitree(&(*bt)->rchild);
- }
- return OK;
- }
按先序次序输入二叉树的结点值,0表示空树。
- 二叉树的遍历(先序、中序、后序)
- void preorder(bitree bt, int (*visit)(elemtype e))
- {
- if (bt) {
- visit(bt->data);
- preorder(bt->lchild, visit);
- preorder(bt->rchild, visit);
- }
- }
- void inorder(bitree bt, int (*visit)(elemtype e))
- {
- if (bt) {
- inorder(bt->lchild, visit);
- visit(bt->data);
- inorder(bt->rchild, visit);
- }
- }
- void postorder(bitree bt, int (*visit)(elemtype e))
- {
- if (bt) {
- postorder(bt->lchild, visit);
- postorder(bt->rchild, visit);
- visit(bt->data);
- }
- }
- 求二叉树的深度
- int get_tree_depth(bitree bt)
- {
- int ldepth, rdepth;
- if (!bt)
- return 0;
- else if (!bt->lchild && !bt->rchild)
- return 1;
- else {
- ldepth = get_tree_depth(bt->lchild);
- rdepth = get_tree_depth(bt->rchild);
- return (ldepth > rdepth ? ldepth : rdepth) + 1;
- }
- }
树的深度即树的结点中最大层次,分别递归求左右子树的深度,较大子树深度为树的深度。
- 求叶子结点数
- int get_num_of_leave(bitree bt)
- {
- if (!bt)
- return 0;
- else if (!bt->lchild && !bt->rchild)
- return 1;
- else
- return (get_num_of_leave(bt->lchild) + get_num_of_leave(bt->rchild));
- }
递归求左右子树的叶子数,左右子树的叶子结点之和为树的叶子结点数。
- 释放二叉树
- void free_bitree(bitree *bt)
- {
- if (*bt) {
- if ((*bt)->lchild)
- free_bitree(&(*bt)->lchild);
- if ((*bt)->rchild)
- free_bitree(&(*bt)->rchild);
- free(*bt);
- *bt = NULL;
- }
- }
- 算法实现源码
免费下载:http://download.csdn.net/detail/algorithm_only/3800074
- 二叉树的二叉链表表示与实现
- 二叉树的二叉链表表示与实现
- 二叉树的二叉链表表示与实现
- 二叉树的二叉链表表示与实现
- 二叉树的二叉链表表示与实现
- 二叉树的二叉链表表示和实现
- 二叉树的链表表示法实现
- 二叉树的链表表示 C++实现
- 二叉树链表表示
- 小程序-----链表表示二叉树
- 静态链表表示二叉树
- 二叉树链表表示法
- 广义表表示二叉树结构生成二叉链表的算法
- 二叉树的查找、二叉树高度、二叉树获得双亲结点、构造二叉树、二叉树的广义表表示法、二叉树的插入删除、二叉树的非递归实现
- 广义表表示树二叉树
- 数据结构——二叉树的孩子链表表示法
- 第6章 树和二叉树——递归方法先序、中序、后序遍历二叉链表表示的二叉树
- 二叉树的二叉链表实现
- UVa 1556 1344
- dll动态链接库(2)---入口函数DllMain
- Invalid character constant
- LibLinear(SVM包)使用说明之(二)MATLAB接口
- Shiro 教程
- 二叉树的二叉链表表示与实现
- poj 1637 Sightseeing tour(混合欧拉回路)
- dll动态链接库(3)---函数调用方式
- Crontab 命令介绍
- 对象序列化与反序列化
- 跟我一起写Makefile文件(四)
- Java 拥塞队列
- Java调用C++webservice接口
- 几个常用的Objective-C开源类库