1161.cpp (643B)
1 class Solution { 2 public: 3 int maxLevelSum(TreeNode *root) { 4 queue<TreeNode *> q; 5 q.push(root); 6 7 int maxi = INT_MIN, index = -1; 8 for (int lvl = 1; !q.empty(); lvl++) { 9 int sum = 0; 10 for (int k = q.size(); k > 0; k--) { 11 TreeNode *root = q.front(); 12 q.pop(); 13 sum += root->val; 14 if (root->left) q.push(root->left); 15 if (root->right) q.push(root->right); 16 } 17 if (sum > maxi) { 18 maxi = sum; 19 index = lvl; 20 } 21 } 22 return index; 23 } 24 };