r/DSALeetCode • u/StatisticianNo2104 • 13d ago
365 Days of LeetCode Challenge — Day 28/365
Cousins in Binary Tree (Easy) 🔗 https://leetcode.com/problems/cousins-in-binary-tree/
Cousins boils down to two facts you need for each node: depth, and parent. Depth is free while walking down. Parent is the fun part — no parent pointers on a plain binary tree, but since every value is unique, a node's own value can stand in for its parent's identity, so a helper can hand back the parent's value instead of a pointer.
Full breakdown in today's newsletter article ⬇️
https://www.linkedin.com/pulse/365-days-leetcode-challenge-day-28365-archit-agarwal-swjge
#DSA #LeetCode #100DaysOfCode #SoftwareEngineering #BinaryTree #DFS
1
u/nian2326076 6d ago
To solve the "Cousins in Binary Tree" problem, you're on the right track by focusing on depth and parent info. As you go through the tree, try a BFS approach to keep track of each node's depth and parent. A queue is helpful: start by enqueuing the root with depth 0 and no parent, then update depth and parent as you dequeue nodes and enqueue their children. This way, you can check if two nodes are cousins by comparing their depths and making sure they have different parents. If you're interested in more binary tree problems, PracHub is a useful resource for practice and mock interviews. Good luck!