[数据结构]求二叉树的深度与宽度
来源:互联网 发布:惠伦模型 知乎 编辑:程序博客网 时间:2024/05/19 20:00
二叉树数据结构声明:
struct TreeNode{ int val; TreeNode *left; TreeNode *right;};
1、递归求二叉树深度
int getDepth(TreeNode *root){ if (root == NULL) { return 0; } return getDepth(root->left) > getDepth(root->right) ?(getDepth(root->left) + 1) : (getDepth(root->right) + 1);}2、宽度优先遍历求二叉树宽度
宽度优先遍历,记录每一个层次的叶子节点,返回最大值
int getWidth(TreeNode *root){ if (root == NULL) { return 0; } int width_up = 0; int temp = 0; int width_cur = 0; int width_res = 0; queue<TreeNode *> myQueue; myQueue.push(root); width_up = 1; width_res=1; TreeNode *temp_TreeNode = NULL; while (!myQueue.empty()) { temp = width_up; while (temp != 0) { temp_TreeNode = myQueue.front(); myQueue.pop(); if (temp_TreeNode->left != NULL) { myQueue.push(temp_TreeNode->left); } if (temp_TreeNode->right != NULL) { myQueue.push(temp_TreeNode->right); } width_up--; } width_cur = myQueue.size(); width_res = width_cur > width_res ? width_cur : width_res; width_up = width_cur; } return width_res;}
0 0
- [数据结构]求二叉树的深度与宽度
- 求二叉树的最大深度与最大宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求C++数据结构二叉树的宽度
- 求二叉树的高度与宽度
- 华为练习 求二叉树的宽度和深度
- 求二叉树的深度和宽度[Java]
- 求二叉树的深度和宽度平衡最大距离
- 求二叉树的深度、宽度和叶子结点数
- 华为oj 求二叉树的深度和宽度
- 求二叉树的深度和宽度[Java]
- 技术与经济之五:关于货币市场
- 廖雪峰javascrip学习笔记<基础>
- 范式
- C专家编程笔记之数组和结构体中的数组
- 从现在看未来,在未来看现在
- [数据结构]求二叉树的深度与宽度
- 解决投影仪放映PPT时左右、上下出现黑边问题
- WebSocket即时聊天
- 3.2.2 正则表达式的功能
- Windows进程间各种通信方式浅谈
- UITextField的UIControlEventValueChanged事件
- Java学习笔记------------如何启用jre包中的:sun.net.ftp
- @IsMember的使用
- CSS的使用