1161. Maximum Level Sum of a Binary Tree
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
class Solution { public: int maxLevelSum(TreeNode* root) { queue<TreeNode*> q; q.push(root); long res = LONG_MIN; int lvl = 1, curLvl = 1; while(!q.empty()) { long sum = 0; int count = q.size(); while(count--) { auto node = q.front(); q.pop(); sum += node->val; if(node->left != nullptr) q.push(node->left); if(node->right != nullptr) q.push(node->right); } if(res < sum) { res = sum; lvl = curLvl; } curLvl++; } return lvl; } };
|