0662.cpp (714B)
1 class Solution { 2 public: 3 int widthOfBinaryTree(TreeNode *root) { 4 if (root == NULL) return 0; 5 queue<pair<TreeNode *, int>> q; 6 7 int res = 1; 8 q.push({root, 0}); 9 while (!q.empty()) { 10 int start = q.front().second, end = q.back().second; 11 12 res = max(res, end - start + 1); 13 for (int k = q.size(); k > 0; k--) { 14 pair<TreeNode *, int> p = q.front(); 15 q.pop(); 16 int idx = p.second - start; 17 18 if (p.first->left) q.push({p.first->left, 2ll * idx + 1}); 19 if (p.first->right) q.push({p.first->right, 2ll * idx + 2}); 20 } 21 } 22 23 return res; 24 } 25 };