leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0662.cpp (714B)


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