Maximum Width of Binary Tree LeetCode solution in C++
1/*2Run BFS and store the index of the node when it was stored in the flattened3manner. Take the diff of each of the level and keep traking of max value45*/6class Solution {7public:8int widthOfBinaryTree(TreeNode *root) {9if (!root) return 0;10int res = 0;11queue<pair<TreeNode *, int>> q;12q.push({root, 0});13while (!q.empty()) {14int n = q.size();15res = max(res, q.back().second - q.front().second + 1);16int start = q.front().second;17while (n--) {18TreeNode *p = q.front().first;19long long ind = q.front().second - start;20q.pop();21if (p->left) q.push({p->left, ind * 2 + 1});22if (p->right) q.push({p->right, ind * 2 + 2});23}24}25return res;26}27};