662. Maximum Width of Binary Tree
https://leetcode.com/problems/maximum-width-of-binary-tree/description/
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int widthOfBinaryTree(TreeNode* root) { int left = 0, right = 0, res = 0; queue<pair<int,TreeNode*>> q; if (root != NULL) q.push({1, root}); while (!q.empty()) { int qsz = q.size(); for (int i = 0; i < qsz; i++) { int idx = q.front().first; TreeNode* cur = q.front().second; q.pop(); if (i == 0) left = idx; if (i == qsz - 1) right = idx; if (cur->left) q.push( { idx *2, cur->left }); if (cur->right) q.push( { idx *2 + 1, cur->right }); } res = max(res, right-left+1); } return res; } };