2641. Cousins in Binary Tree II | Tree | BFS | Binary Tree | O(N) | LeetCode | Medium

Опубликовано: 23 Июнь 2026
на канале: Leet's Code
65
2

🚀 LeetCode Problem 2641: Cousins in Binary Tree II | C++ Solution Walkthrough 🚀

In this video, we’ll tackle LeetCode problem 2641 - Cousins in Binary Tree II. We’ll explore how to solve the problem by modifying a binary tree and replacing each node’s value with the sum of its cousins' values using an efficient BFS (Breadth-First Search) approach.

Problem Link :- https://leetcode.com/problems/cousins...
Code Link:- https://leetcode.com/submissions/deta...

🔍 Problem Overview: The task is to update each node in a binary tree by replacing its value with the sum of the values of its cousin nodes. Cousins are nodes that share the same level but have different parents. This problem is perfect for mastering binary tree traversal and level-order processing.

🛠️ What You’ll Learn:

How to implement level-order traversal using a queue
Techniques to calculate and update cousin values efficiently
Key insights into working with binary trees in C++
💡 Approach Breakdown:

Start by initializing the root node with a value of 0.
Perform a level-order traversal of the binary tree using a queue.
Calculate the sum of all nodes at each level, excluding a node's direct children, and update their values with the corresponding sum.
Return the modified tree.
By the end of the video, you'll understand the step-by-step logic to solve this problem and enhance your skills in solving binary tree problems on LeetCode.

🎯 Perfect For:

Developers looking to improve their binary tree and BFS skills
Anyone preparing for coding interviews
Those practicing for competitive programming challenges
💻 Watch, Learn, and Practice with this comprehensive solution and explanation!

🔔 Don't forget to LIKE, COMMENT, and SUBSCRIBE for more coding tutorials and solutions to top LeetCode problems!

#LeetCode #BinaryTree #CodingInterview #CousinsInBinaryTree #CPlusPlus #BFS #ProgrammingTutorial