662 二叉树最大宽度

本文最后更新于:2021年7月7日 晚上

给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。

每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。

示例 1:

1
2
3
4
5
6
7
8
9
10
输入: 

1
/ \
3 2
/ \ \
5 3 9

输出: 4
解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。

示例 2:

1
2
3
4
5
6
7
8
9
10
输入: 

1
/
3
/ \
5 3

输出: 2
解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。

示例 3:

1
2
3
4
5
6
7
8
9
10
输入: 

1
/ \
3 2
/
5

输出: 2
解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。

示例 4:

1
2
3
4
5
6
7
8
9
10
11
输入: 

1
/ \
3 2
/ \
5 9
/ \
6 7
输出: 8
解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。

注意: 答案在32位有符号整数的表示范围内。

Solution

参考:@zrita

  • 队列元素使用pair,多用一个int值记录当前层的索引

  • 左子树是父节点的index * 2,右子树是 index * 2 + 1,减去start * 2 便是在该层的位置,用于防止索引太大溢出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if (root == nullptr) return 0;
int res = 0;
queue<pair<TreeNode*, int>> que; // 第二个位置记录当前是第几个节点
que.push({root, 1});

// 层序遍历
while (!que.empty()) {
int cnt = que.size();
res = max(res, que.back().second - que.front().second + 1);
int start = que.front().second; // 本层的起点索引
while (cnt--) {
TreeNode* node = que.front().first;
int index = que.front().second;
que.pop();
if (node->left)
que.push({node->left, index*2-start*2}); // 防止索引值太大溢出
if (node->right)
que.push({node->right, index*2+1-start*2});
}
}
return res;
}
};
// @lc code=end

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!