Leetcode 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.
The binary tree can have a maximum height of 1000 and a maximum number of nodes as 3000.
null
nodes between the end-nodes treated in the width calculation?
null
nodes at intermediate levels?
#include <iostream>
#include <queue>
#include <utility>
#include <limits.h>
using namespace std;
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) return 0;
// Queue will store pairs of TreeNode* and its position index
queue<pair<TreeNode*, unsigned long long>> q;
q.push({root, 0});
unsigned long long maxWidth = 0;
while (!q.empty()) {
int size = q.size();
unsigned long long minIndex = q.front().second;
unsigned long long first, last;
for (int i = 0; i < size; ++i) {
unsigned long long curIndex = q.front().second - minIndex; // Normalize to prevent overflow
TreeNode* node = q.front().first;
q.pop();
if (i == 0) first = curIndex;
if (i == size - 1) last = curIndex;
if (node->left) q.push({node->left, 2 * curIndex + 1});
if (node->right) q.push({node->right, 2 * curIndex + 2});
}
maxWidth = max(maxWidth, last - first + 1);
}
return maxWidth;
}
};
last - first + 1
and keep updating the maximum width.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?