Cousins in Binary Tree
Problem Statement
You are given the root of a binary tree, where every value is different, and two values x and y. Both values are in the tree, and they are not equal.
Return true if the nodes holding x and y are cousins, otherwise return false.
Two nodes are cousins when they are on the same depth and have different parents. The root is at depth 0, and the children of a node at depth k are at depth k + 1.
The root of a binary tree, and two different values x and y. Every value in the tree is unique, and both x and y exist in it.
true if the two nodes are cousins, otherwise false.
4 is at depth 2 and 3 is at depth 1. They are on different depths.
4 is at depth 2 under 2, and 5 is at depth 2 under 3. Same depth, different parents.
2 and 3 are both children of the root. Same depth, but the same parent, so they are siblings and not cousins.
- β’ The number of nodes is between 2 and 100.
- β’ 1 β€ Node.val β€ 100
- β’ Every node has a unique value.
- β’ x β y
- β’ x and y both exist in the tree.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Search for x and record its depth and parent; do the same for y; then compare the two records
Walk one depth at a time; in each round check each node's children for a sibling pair, then check whether both values were seen
Run one depth-first search for x that records its depth and its parent. Run a second search for y the same way. The answer is true when the two depths are equal and the two parents are different.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree BFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.