← Home

1315. Sum of Nodes with Even-Valued Grandparent

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
131

This is one of those problems where the clean idea matters more than the amount of code. For 1315. Sum of Nodes with Even-Valued Grandparent, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, sliding window.

The notes already sitting in the source point us in the right direction:

  • Hint 1 : Traverse the tree keeping the parent and the grandparent.
  • Hint 2 : If the grandparent of the current node is even-valued, add the value of this node to the answer.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are sumEvenGrandparent.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Hint 1 : Traverse the tree keeping the parent and the grandparent.
02//Hint 2 : If the grandparent of the current node is even-valued, add the value of this node to the answer.
03
04/*
05Runtime: 56 ms, faster than 25.02% of C++ online submissions for Sum of Nodes with Even-Valued Grandparent.
06Memory Usage: 31.5 MB, less than 100.00% of C++ online submissions for Sum of Nodes with Even-Valued Grandparent.
07*/
08
09/**
10 * Definition for a binary tree node.
11 * struct TreeNode {
12 *     int val;
13 *     TreeNode *left;
14 *     TreeNode *right;
15 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
16 * };
17 */
18class Solution {
19public:
20    int sumEvenGrandparent(TreeNode* root) {
21        std::stack<TreeNode*> stk;
22        std::stack<int> parents, grandparents;
23        int parent, grandparent;
24        TreeNode *node;
25        int ans = 0;
26        
27        stk.push(root);
28        //The value of nodes is between 1 and 100.
29        parents.push(0);
30        grandparents.push(0);
31        
32        while(!stk.empty()){
33            node = stk.top(); stk.pop();
34            parent = parents.top(); parents.pop();
35            grandparent = grandparents.top(); grandparents.pop();
36            
37            if(grandparent != 0 && grandparent % 2 == 0){
38                ans += node->val;
39            }
40            
41            if(node->right){
42                stk.push(node->right);
43                parents.push(node->val);
44                //current node's parent is its child's grandparent
45                grandparents.push(parent);
46            }
47            
48            if(node->left){
49                stk.push(node->left);
50                parents.push(node->val);
51                //current node's parent is its child's grandparent
52                grandparents.push(parent);
53            }
54        }
55        
56        return ans;
57    }
58};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.