考察知识点: 广度优先搜索、树的层序遍历、STL

题目分析:

 本题要求求出二叉树中和最大的那一层。可以层序遍历这个二叉树,遍历过程中维护重量级的那一层的数值和索引。

 树的层序遍历一般使用一个队列,先将头节点放入队列中,然后对队列中的每个元素,首先访问这个元素,然后将该元素的左右孩子结点放入队列中,直至队列中为空。

所用编程语言: C++

/**
 * 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) return {};
        queue<TreeNode*> cows;
        cows.push(root);
        int maxCows = 0;
        int index = -1;
        int floor = 0;
        while (!cows.empty()) {
            floor++;
            int size = cows.size();
            int sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode *p = cows.front();
                cows.pop();
                sum += p->val;
                if (p->left) cows.push(p->left);
                if (p->right) cows.push(p->right);
            }
            if (sum >= maxCows) {
                maxCows = sum;
                index = floor;
            }
        }
        return index;
    }
};