class Solution {
public:
struct node {
TreeNode* root;
long double site;//用个样例血坑必须扩大范围不然过不了
};
node start,end,tmp,temp;
queue<node> que;long double curLayer=1,index=1,max_len=0;
int widthOfBinaryTree(TreeNode* root) {
start.root = root;start.site = 1;
que.push(start);
while(!que.empty()) {
tmp = que.front();que.pop();
if(tmp.root->left) {
temp.root = tmp.root->left;temp.site = 2*tmp.site;
que.push(temp);
}
if(tmp.root->right) {
temp.root = tmp.root->right;temp.site = 2*tmp.site+1;
que.push(temp);
}
curLayer--;
if(curLayer==0) {
curLayer = que.size();
max_len = max(max_len,tmp.site-start.site+1);
start = que.front();
}
}
return max_len;
}
};
LeetCode:二叉树最大宽度
最新推荐文章于 2023-01-14 09:07:42 发布
本文介绍了一种计算二叉树最大宽度的算法。通过宽度优先遍历,使用队列存储节点及其位置信息,每次迭代更新当前层的节点数量和最大宽度。此算法能够有效地处理大规模二叉树结构。
685

被折叠的 条评论
为什么被折叠?



