题解 | #重量级的一层#
重量级的一层
https://www.nowcoder.com/practice/193372871b09426ab9ea805f0fd44d5c
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ int maxLevelSum(TreeNode* root) { // write code here if (root == NULL) { return 0; } queue<TreeNode*> que; que.push(root); int result = 0; int maxWeight = 0; int level = 0; while (!que.empty()) { int n = que.size(); int num = 0; level++; for (int i = 0;i < n;++i) { TreeNode* node = que.front(); que.pop(); num += node->val; if (node->left) { que.push(node->left); } if (node->right) { que.push(node->right); } } if (num >= maxWeight) { maxWeight = num; result = level; } } return result; } };