链式二叉树
2016-07-11 21:23
239 查看
# include <stdio.h> # include <stdlib.h> # include <malloc.h> struct NODE { char ch; struct NODE *lchild; struct NODE *rchild; }; struct NODE *CreateTree(void); bool is_empty(struct NODE *p); int depth(struct NODE *p); bool traverse(struct NODE *p); bool destory(struct NODE *p); void visit(char ch); int main() { struct NODE *root = CreateTree(); if ( is_empty(root) ) printf("是空树\n"); else printf("不是空树\n"); int depths = depth(root); printf("depth is %d\n", depths); traverse(root); destory(root); return 0; } /* 功能:先序创建二叉树 返回:创建的节点地址 */ struct NODE *CreateTree(void) { char ch; struct NODE *p = NULL; scanf("%c", &ch); if (' ' == ch) { return p; } else { p = (struct NODE *)malloc(sizeof(struct NODE)); p->ch = ch; p->lchild = CreateTree(); p->rchild = CreateTree(); return p; } } /* 功能:判断该二叉树是否为空 返回:true 空; false 非空 */ bool is_empty(struct NODE *p) { if (p == NULL) return true; else return false; } /* 功能:求二叉树的深度 */ int depth(struct NODE *p) { int l; //左子树的深度 int r; //右子树的深度 if (p == NULL) { return 0; } if ( p->lchild ) { l = depth(p->lchild); } else { l = 0; } if ( p->rchild ) { r = depth(p->rchild); } else { r = 0; } return (l>r) ? (l+1) : (r+1); } /* 功能:先序遍历二叉树 */ bool traverse(struct NODE *p) { if (!p) return true; traverse(p->lchild); traverse(p->rchild); visit(p->ch); return true; } /* 功能: 销毁二叉树 */ bool destory(struct NODE *p) { if (p) { if (p->lchild) { destory(p->lchild); } if (p->rchild) { destory(p->rchild); } free(p); p = NULL; } return true; } void visit(char ch) { printf("%c ", ch); }
相关文章推荐
- thinkphp项目 出现 Internal Server Error 错误原因分析
- Java变量
- 第99章、Android调用Javascript(从零开始学Android)
- 非常简单的入门git操作
- CentOS 6.5 安装nginx及负载均衡配置
- 自行车比赛+纪中1238+tarjan缩点+拓扑排序+玄学优化
- java访问修饰符
- 制作docker image
- struts2 学习路线
- Java注解——这些@圈圈都是个啥?
- cookie 和session 的区别详解
- 实战Angular2+web api增删改查 (一)
- 非随机快速排序C语言实现
- 有序数组问题的思考
- Git2--创建版本库,版本回退
- leetcode.184. Department Highest Salary
- 二进制中1的个数
- 在Ubuntu 14.04 安装 JDK
- poj 1015 Jury Compromise
- android JSONObject中对key-value为null的特殊处理