二叉树的最大宽度
发布日期:2021-10-10 05:31:25 浏览次数:50 分类:技术文章

本文共 1363 字,大约阅读时间需要 4 分钟。

二叉树的最大宽度

文章目录

代码

// the max depth for the binary tree// use the recursion to deal it // use the circulation to deal it // sometime the recurtion idea is not a good idea#ifndef _BIN_TREE_MAX_DEEP_LENGTH#define _BIN_TREE_MAX_DEEP_LENGTH#include 
#include
int max(int a, int b) { return (a > b? a: b);}struct TreeNode { int value; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : value(x), left(NULL), right(NULL) { }};class Solution {public: Solution() {}; virtual ~Solution() {};public: int TreeWidth(TreeNode * root) { if (NULL == root) { return 0; } std::queue
level_node_queue; level_node_queue.push(root); int max_width_total = 0; int max_width_level = 0; while(!level_node_queue.empty()) { max_width_level = level_node_queue.size(); // 当前层的宽度 max_width_total = max(max_width_total, max_width_level); for (int i = 0; i < max_width_level; ++i) { // 把当前层的节点导出,并且导入下一层node auto node = level_node_queue.pop(); if (!node->left) level_node_queue.push(node->left); if (!node->right) level_node_queue.push(node->right); } } return max_width_total; }};#endif

转载地址:https://blog.csdn.net/qq_22054285/article/details/87373287 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:c/c++内存对齐
下一篇:linux下so编写 - 动态库-类

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月19日 04时30分29秒