二叉树递归、非递归求深度
来源:互联网 发布:判断在数组里面 php 编辑:程序博客网 时间:2024/05/29 04:46
(一)递归求深度
int TreeDeepth_Recur(TreeNode *root){ if(root == NULL) return 0; int left_deepth, right_deepth ; left_deepth = TreeDeepth_Recur(root->left); right_deepth = TreeDeepth_Recur(root->right); return (left_deepth > right_deepth)?left_deepth + 1:right_deepth + 1;}(二)非递归求深度
采用BFS的思想,记录每层的深度,遍历到最后一层后,所记录的深度就是整棵树的深度。
int TreeDeepth(TreeNode *root){ if(root == NULL) return 0; typedef std::pair<TreeNode*, int> PTI; queue<PTI> q; q.push(PTI(root, 1)); PTI curnode ; int curdeepth = 1; //用于记录深度 while(!q.empty()){ curnode = q.front(); q.pop(); curdeepth = curnode.second; if(curnode.first->left) q.push(PTI(curnode.first->left, curnode.second + 1)); if(curnode.first->right) q.push(PTI(curnode.first->right, curnode.second + 1)); } return curdeepth;}调用接口:
int main(void){ TreeNode *root = NULL; PreoderBuildTree(root); std::cout << TreeDeepth_Recur(root); std::cout << std::endl; std::cout << TreeDeepth(root); std::cout << std::endl;}
0 0
- 二叉树递归、非递归求深度
- 二叉树非递归求深度
- 非递归求二叉树的深度
- 求二叉树的深度,递归与非递归算法
- 求二叉树的深度递归与非递归版
- 二叉树的遍历,递归和非递归,求深度
- 求二叉树深度 -- 递归和非递归实现
- 递归与非递归求二叉树深度
- 求二叉树深度的递归和非递归算法
- 求二叉树的深度 递归 非递归
- 二叉树的非递归遍历&求深度
- 求二叉树深度的非递归算法
- 二叉树非递归求深度和节点个数
- 判断完全二叉树以及求二叉树深度的递归与非递归算法实现
- 二叉树(4)----求二叉树深度,递归和非递归
- 二叉树·求深度·遍历·递归非递归(C++)
- C++ 实现求二叉树的深度及遍历(递归与非递归算法)
- 二叉树,递归、非递归遍历,求深度,输出叶子节点
- 牛客网一站通Offer考试第一题
- 每天一篇python:执行shell命令
- 细读百度地图点聚合源码(上)
- 设计模式学习--命令模式
- 学习排序 Learning to Rank 小结
- 二叉树递归、非递归求深度
- css3 之 border-sizing
- Sharepoint 轻量化应用之初试面谈表单制作!
- 欢迎使用CSDN-markdown编辑器
- cmd连接mysql的方法详解
- 电子相册系统(九)分页
- hdoj 1559 最大子矩阵
- Android API Guides---Spelling Checker Framework
- 巩固C语言(十二)----文件加解密