The Cousins in Binary Tree II coding problem is a "Medium" variation where you are asked to transform the tree. For each node, you must replace its value with the sum of all its cousins' values. A cousin is defined as a node at the same depth with a different parent. If a node has no cousins, its new value should be 0.
Google and Amazon ask this binary tree interview pattern to test your ability to perform multi-pass tree manipulations. It requires calculating level-wide sums and then subtracting sibling values to isolate cousin values. It evaluates your proficiency with Breadth-First Search (BFS) and level-order data aggregation.
This problem is best solved using a Two-Pass BFS.
(Total sum of level d) - (Sum of values of this node and its siblings).Level 2 nodes: A(val 10, parent P1), B(val 20, parent P1), C(val 30, parent P2).
When a problem asks for "all nodes in level EXCEPT siblings," the formula (Level Total) - (Sibling Total) is a very powerful optimization that avoids searching for individual cousins.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Lowest Common Ancestor of Deepest Leaves | Medium | Solve | |
| Correct a Binary Tree | Medium | Solve | |
| Clone Binary Tree With Random Pointer | Medium | Solve | |
| Find Distance in a Binary Tree | Medium | Solve | |
| Amount of Time for Binary Tree to Be Infected | Medium | Solve |