Skip to content

Latest commit

 

History

History

1315

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given a binary tree, return the sum of values of nodes with even-valued grandparent.  (A grandparent of a node is the parent of its parent, if it exists.)

If there are no nodes with an even-valued grandparent, return 0.

 

Example 1:

Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.

 

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.

Related Topics:
Tree, Depth-first Search

Solution 1. Pre-order Traversal

// OJ: https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
    int ans = 0;
    vector<TreeNode*> v;
    void preorder(TreeNode *root, int level) {
        if (!root) return;
        if (v.size() <= level) v.push_back(root);
        else v[level] = root;
        if (level - 2 >= 0 && v[level - 2]->val % 2 == 0) ans += root->val;
        preorder(root->left, level + 1);
        preorder(root->right, level + 1);
    }
public:
    int sumEvenGrandparent(TreeNode* root) {
        preorder(root, 0);
        return ans;
    }
};