<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 {
public:
    void levels(TreeNode* root, int level, vector<vector<int>> &Nodes)
    {
        if( !root ) return;
        else
        {
            if( level >= Nodes.size() )
            {
                vector<int> nodes_level;
                nodes_level.push_back( root->val );
                Nodes.push_back( nodes_level );
                levels( root->left,  level+1, Nodes);
                levels( root->right, level+1, Nodes);
            }
            else
            {
                Nodes[level].push_back( root->val );
                levels( root->left,  level+1, Nodes);
                levels( root->right, level+1, Nodes);
            }
        }
    }

    int maxLevelSum(TreeNode* root) 
    {
        vector<vector<int>> sum_level;
        if( !root ) return 0;
        levels( root, 0, sum_level );

        int max_sum_level = root->val;
        int max_level     = 1;

        for(int i=1; i<sum_level.size(); i++)
        {
            int sum = sum_level[i][0];

            for(int o=1; o<sum_level[i].size(); o++)
            {
                sum += sum_level[i][o]; 
            } 

            if( sum > max_sum_level ) 
            {
                max_level = i+1;
                max_sum_level = sum;
            }
        }

        return max_level;
    }
};
107300