<p>Given the <code>root</code> of a binary tree, the level of its root is <code>1</code>, the level of its children is <code>2</code>, and so on.</p>

<p>Return the <strong>smallest</strong> level <code>x</code> such that the sum of all the values of nodes at level <code>x</code> is <strong>maximal</strong>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2019/05/03/capture.JPG" style="width: 200px; height: 175px;" />
<pre>
<strong>Input:</strong> root = [1,7,0,7,-8,null,null]
<strong>Output:</strong> 2
<strong>Explanation: </strong>
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> root = [989,null,10250,98693,-89388,null,null,null,-32127]
<strong>Output:</strong> 2
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>

/**
 * 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
{
private:
    using SumMap = std::unordered_map<int, int>;
    using NodesQueue = std::queue<std::pair<TreeNode *, int>>;

    void maxLevelSumImpl(TreeNode *root, int level, SumMap &sum_map, NodesQueue &queue)
    {
        if (root == nullptr)
            return;

        if (root->left != nullptr)
            queue.push({root->left, level});
        if (root->right != nullptr)
            queue.push({root->right, level});

        if (!queue.empty())
        {
            auto front = queue.front();
            queue.pop();

            auto sum = sum_map.find(front.second);
            if (sum != sum_map.end())
            {
                sum->second += front.first->val;
            }
            else
            {
                sum_map[front.second] = front.first->val;
            }

            maxLevelSumImpl(front.first, front.second + 1, sum_map, queue);
        }
    }

public:
    int maxLevelSum(TreeNode *root)
    {
        SumMap sum_map;
        NodesQueue queue;

        using SumMapPair = decltype(sum_map)::value_type;

        sum_map[1] = root->val;
        maxLevelSumImpl(root, 2, sum_map, queue);

        return std::max_element(sum_map.begin(), sum_map.end(), [](const SumMapPair &a, const SumMapPair &b) -> bool
                                { return a.second <= b.second; })
            ->first;
    }
};
110600