[LeetCode] Maximum Width of Binary Tree

662. Maximum Width of Binary Tree

Given the root of a binary tree, return the maximum width of the given tree.

The maximum width of a tree is the maximum width among all levels.

The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.

It is guaranteed that the answer will in the range of 32-bit signed integer.

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
/**
* 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 {
map<int, pair<long long,long long>> m;
int result() {
unsigned long long res(0);
for(auto& e : m) {
res = max(res, e.second.second - e.second.first + 1);
}
return res;
}
public:
int widthOfBinaryTree(TreeNode* root, int depth = 0, unsigned long long pos = 0) {
if(!root) return 0;
if(!m.count(depth)) {
m[depth] = {ULLONG_MAX, 0};
}
m[depth].first = min(m[depth].first, pos);
m[depth].second = max(m[depth].second, pos);
if(root->left) widthOfBinaryTree(root->left, depth + 1, pos * 2);
if(root->right) widthOfBinaryTree(root->right, depth + 1, pos * 2 + 1);
return depth ? -1 : result();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/14/PS/LeetCode/maximum-width-of-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.