大家好,我是开车的阿Q,自动驾驶的时代已经到来,没时间解释了,快和阿Q一起上车。作为自动驾驶系统工程师,必须要有最好的C++基础,让我们来一起刷题吧。
题目考察的知识点
二叉树遍历,层次遍历
题目解答方法的文字分析
我们需要逐层遍历二叉树并计算每一层的牛的总重量。可以通过层次遍历来实现这个目标,同时使用一个队列来辅助。层次遍历的基本思路是:从根节点开始,依次将每一层的节点入队,然后逐个出队,计算当前层的总重量,并将下一层的节点继续入队。在这个过程中,我们可以记录每一层的总重量,并找到总重量最大的层。
例如,对于示例1中的二叉树 {500, 600, 600, 700, 800},层次遍历的结果为:
- 第1层:500
- 第2层:600, 600
- 第3层:700, 800
最大总重量为第3层的 700 + 800 = 1500,因此返回 3。
本题解析所用的编程语言
C++
完整且正确的编程代码
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: int maxLevelSum(TreeNode* root) { if (!root) { return 0; // 空树返回0 } int maxSum = INT_MIN; // 最大总重量 int maxLevel = 0; // 最大总重量的层级 int level = 1; // 当前层级 queue<TreeNode*> q; q.push(root); while (!q.empty()) { int size = q.size(); // 当前层的节点数量 int currentSum = 0; // 当前层的总重量 for (int i = 0; i < size; i++) { TreeNode* node = q.front(); q.pop(); currentSum += node->val; if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } if (currentSum > maxSum) { maxSum = currentSum; maxLevel = level; } level++; } return maxLevel; } };