1161. 最大层内元素和

代码实现(自解)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxLevelSum(TreeNode* root) {
int maxSum = INT_MIN, maxLevel = 0;
queue<TreeNode*> _queue;
int curSum = 0, curLevel = 0, sz = 0;
TreeNode* curNode = NULL;
_queue.push(root);
while (!_queue.empty()) {
sz = _queue.size();
curSum = 0;
curLevel++;
while (sz--) {
curNode = _queue.front();
_queue.pop();
curSum += curNode->val;
if (curNode->left) _queue.push(curNode->left);
if (curNode->right) _queue.push(curNode->right);
}
if (curSum > maxSum) {
maxSum = curSum;
maxLevel = curLevel;
}
}
return maxLevel;
}
};
本文介绍了一种使用广度优先搜索算法解决二叉树中最大层内元素和问题的C++实现。通过维护当前层节点和总和,找到最大层的和及其对应的层级。适用于面试题或理解递归遍历的应用。
9734

被折叠的 条评论
为什么被折叠?



