3 minutes
Leetcode July: Max Width of Binary Tree
Today’s Leetcode July Challenge problem is a neat little binary tree variation. The problem presents us with the root of a binary tree and asks us to return that tree’s maximum width. The maximum width here is defined as the maximum number of nodes between the leftmost and rightmost nodes of a single level in the tree. The problem description is a little confusing, but a simple example clears things up. Let’s look at a potential input tree–node values are omitted as they have no bearing on this problem.
Input:
Max Width = 4
Looking at this representation, it’s pretty easy to operationalize for any given node, $n$, its level ordered position value, $op_n$. For any left child node, $op_n = 2\cdot op_{parentnode_n}\;$, and for any right child node $op_n = 2\cdot op_{parentnode_n}+1$. Using this method, as opposed more intuitively counting nodes in a level order traversal, we can account for null nodes between the leftmost and rightmost nodes in a given level.
int widthOfBinaryTree(TreeNode* root) {
if(!root) return 0;
int maxWidth = 0;
// store the each node with its ordered position as a pair, could also make a struct
// to associate the values, but seems unecessary here.
queue<pair<TreeNode*,unsigned long long>> q;
q.push({root, 1});
while(!q.empty()) {
// add 1 to the distance between the nodes to get the inclusive width.
// have to cast width difference to int for comparison with maxWidth.
maxWidth = max(maxWidth, (int)(q.back().second - q.front().second) + 1);
int levelSize = q.size();
for(int i=0;i<levelSize;i++) {
auto [node, position] = q.front();
q.pop();
// the other option to handle integer overflow would be cast position to a long and
// allow an implicit cast back to int, which would likely truncate the highest
// significant digits, but is compliler dependent and undefined behaviour.
if(node->left) q.push({node->left, position*2});
if(node->right) q.push({node->right, position*2+1});
}
}
return maxWidth;
}
That was a fun little problem with a touch of edge case wrangling that you can see in the code comments above. Check back tomorrow to see another problem!