<p>Given the <code>root</code> of a binary tree, return <em>the sum of values of nodes with an <strong>even-valued grandparent</strong></em>. If there are no nodes with an <strong>even-valued grandparent</strong>, return <code>0</code>.</p>

<p>A <strong>grandparent</strong> of a node is the parent of its parent if it exists.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/even1-tree.jpg" style="width: 504px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
<strong>Output:</strong> 18
<strong>Explanation:</strong> The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/even2-tree.jpg" style="width: 64px; height: 65px;" />
<pre>
<strong>Input:</strong> root = [1]
<strong>Output:</strong> 0
</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>1 &lt;= Node.val &lt;= 100</code></li>
</ul>

class Solution {
public:
    int grandsum(TreeNode* node){
        int ans = 0;
        if(node -> left){
            TreeNode* temp = node -> left;
            if(temp -> left) ans += temp -> left -> val;
            if(temp -> right) ans += temp -> right -> val;
        }
        if(node -> right){
            TreeNode* temp = node -> right;
            if(temp -> left) ans += temp -> left -> val;
            if(temp -> right) ans += temp -> right -> val;
        }
        return ans;
    }
    map<int, vector<TreeNode*>> findeven(TreeNode* root){
        queue<pair<TreeNode*, int>> q;
        q.push({root, 0});
        map<int, vector<TreeNode*>> m;
        while(!q.empty()){
            TreeNode* node = q.front().first; int height = q.front().second; q.pop();
            if(node -> val % 2 == 0){
                m[height].push_back(node);
            }
            if (node -> left) q.push({node -> left, height +1});
            if(node -> right) q.push({node -> right, height + 1});
        }
        return m;
    }
    int sumEvenGrandparent(TreeNode* root) {
        if (root == NULL ) return 0;

        map<int, vector<TreeNode*>> m = findeven(root);
        int res = 0;
        for(auto it : m){
            for(auto kt : it.second){
                res += grandsum(kt);
            }
        }
        return res;        
    }
};
43400