递归按层遍历二叉树算法
来源:互联网 发布:lol挂机辅助软件 编辑:程序博客网 时间:2024/05/21 20:32
递归模拟队列按层遍历二叉树,简单,易懂,先序创建二叉树Create_tree(),递归求树深度depth,一层层递归打印节点!
/* * author : qiu * coding : utf-8 * time : 2014-12-- * fun:递归按层遍历二叉树 **/#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <iostream>#include <algorithm>#include <string>#include <vector>#include <malloc.h>#define debug puts("-----")#define pi (acos(-1.0))#define eps (1e-8)#define inf (1<<28)using namespace std;typedef struct bnode{ int data; struct bnode *lchild; struct bnode *rchild; }bnode, *btree;// 先序创建二叉树void Create_tree(btree &root){ int num; scanf("%d", &num); if(num != -1){ root=(btree)malloc(sizeof(bnode)); root->data=num; Create_tree(root->lchild); Create_tree(root->rchild); } else { root = NULL; }}// 递归节点void Printree_level(btree root, int level){ if(!root || level < 1){ return ; } if(level == 1) printf("%d ", root->data); Printree_level(root->lchild, level-1); Printree_level(root->rchild, level-1);}// 树深度int Depth_tree(btree root){ int lcount, rcount; if(!root) return 0; else{ lcount = Depth_tree(root->lchild); rcount = Depth_tree(root->rchild); if(lcount < rcount) return rcount + 1; else return lcount + 1; }}// 按层遍历打印void Printree_traverse(btree root){if(!root)return ; int depth = Depth_tree(root); for(int i=1; i<=depth; i++){ Printree_level(root, i); } printf("\n");}int main(){ btree Root; Create_tree(Root); Printree_traverse(Root);return 0;}
0 0
- 递归按层遍历二叉树算法
- 【数据结构与算法】二叉树的遍历(递归遍历、非递归遍历、层序遍历)
- 二叉树遍历算法集合(前中后序遍历的递归和非递归算法,层序遍历算法)
- 二叉树遍历算法集合(前中后序遍历的递归和非递归算法,层序遍历算法)
- 二叉树遍历算法集合(前中后序遍历的递归和非递归算法,层序遍历算法)
- 二叉树遍历算法集合(前中后序遍历的递归和非递归算法,层序遍历算法)
- 二叉树遍历算法集合(前中后序遍历的递归和非递归算法,层序遍历算法)
- 二叉树遍历递归算法
- 算法:二叉树递归遍历
- 二叉树遍历:递归+非递归+逐层遍历
- 二叉树的非递归按层遍历
- 漫谈二叉树之非递归遍历算法(两种不同思路)+层序遍历
- 二叉树----节点个数、高度、递归和非递归遍历、按层遍历
- 二叉树----节点个数、高度、递归和非递归遍历、按层遍历
- 二叉树遍历(递归,非递归,层序)
- 二叉树的三种非递归遍历及层序遍历
- JAVA中二叉树非递归算法前序,中序,层序遍历
- 二叉树的前序/中序/后序/层序的非递归遍历算法
- java并发包的CAS操作
- Pull解析XML格式数据
- 屏幕解锁
- WebServices测试之一-----UFT测试WEBSERVICES
- LCOJ - Intersection of Two Linked Lists
- 递归按层遍历二叉树算法
- twisted入门教程之三:初步认识Twisted
- 公差等级
- Android中ListView之ArrayAdapter的使用
- twisted入门教程之四:由Twisted支持的诗歌客户端
- java 如何检测内在泄漏呢
- SAX解析XML格式数据
- twisted入门教程之五:由Twited支持的诗歌下载服务客户端
- 卡方分布