1315. Sum of Nodes with Even-Valued Grandparent LeetCode Solution

In this guide, you will get 1315. Sum of Nodes with Even-Valued Grandparent LeetCode Solution with the best time and space complexity. The solution to Sum of Nodes with Even-Valued Grandparent problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sum of Nodes with Even-Valued Grandparent solution in C++
  4. Sum of Nodes with Even-Valued Grandparent solution in Java
  5. Sum of Nodes with Even-Valued Grandparent solution in Python
  6. Additional Resources
1315. Sum of Nodes with Even-Valued Grandparent LeetCode Solution image

Problem Statement of Sum of Nodes with Even-Valued Grandparent

Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.
A grandparent of a node is the parent of its parent if it exists.

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.

Example 2:

Input: root = [1]
Output: 0

Constraints:

The number of nodes in the tree is in the range [1, 104].
1 <= Node.val <= 100

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(h)

1315. Sum of Nodes with Even-Valued Grandparent LeetCode Solution in C++

class Solution {
 public:
  int sumEvenGrandparent(TreeNode* root) {
    return dfs(root, 1, 1);  // The parent and the grandparent are odd at first.
  }

 private:
  int dfs(TreeNode* root, int p, int gp) {
    if (root == nullptr)
      return 0;
    return (gp % 2 == 0 ? root->val : 0) +  //
           dfs(root->left, root->val, p) +  //
           dfs(root->right, root->val, p);
  }
};
/* code provided by PROGIEZ */

1315. Sum of Nodes with Even-Valued Grandparent LeetCode Solution in Java

class Solution {
  public int sumEvenGrandparent(TreeNode root) {
    return dfs(root, 1, 1); // The parent and the grandparent are odd at first.
  }

  private int dfs(TreeNode root, int p, int gp) {
    if (root == null)
      return 0;
    return (gp % 2 == 0 ? root.val : 0) + //
        dfs(root.left, root.val, p) +     //
        dfs(root.right, root.val, p);
  }
}
// code provided by PROGIEZ

1315. Sum of Nodes with Even-Valued Grandparent LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

See also  1882. Process Tasks Using Servers LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.