In this tree-based challenge, you are given a binary tree. Your goal is to find the sum of all nodes that have an "even-valued grandparent." A node's grandparent is the parent of its parent. If a node has a grandparent and that grandparent's value is an even number, the node's value should be added to the total sum.
Companies like Microsoft, Meta, and Salesforce ask this problem to test a candidate's ability to traverse a tree while maintaining context from ancestor nodes. It's a classic example of how to pass information down a recursive call stack. It evaluates whether you can handle the "lookback" logic without actually storing a full path for every node, which would be memory-inefficient.
The primary pattern is Depth-First Search (DFS) with state propagation. As you traverse the tree, each recursive call passes two additional pieces of information: the value of the current node's parent and the value of the current node's grandparent.
u, if grandparent_val is even, add u.val to the sum.u, the current u.val becomes the "parent" for the children, and the current "parent" becomes the "grandparent."Consider the following tree fragment:
6 (Grandparent)
/
7 (Parent)
/
2 7 (Nodes to check)
node.left.left, node.left.right, etc. This leads to many null-pointer checks and messy code. Passing state down is much cleaner.Practice passing "state" through recursion. Many tree and graph problems require knowing something about the path taken to reach the current node. This technique avoids the need for complex "parent" pointers or global arrays.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Good Nodes in Binary Tree | Medium | Solve | |
| Find Largest Value in Each Tree Row | Medium | Solve | |
| Find Bottom Left Tree Value | Medium | Solve | |
| Reverse Odd Levels of Binary Tree | Medium | Solve | |
| Maximum Level Sum of a Binary Tree | Medium | Solve |