LeetCode 2641: Cousins in Binary Tree II Solution
Master LeetCode problem 2641 (Cousins in Binary Tree II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2641. Cousins in Binary Tree II
Problem Explanation
Explanation:
- We will perform a level-order traversal of the binary tree.
- While traversing each level, we will keep track of the nodes that are cousins and calculate their sum.
- We will update the node values with the sum of their cousins' values.
- To identify cousins, we will keep track of the parent node of each node.
- We will use a queue to perform the level-order traversal.
Time Complexity: O(N) where N is the number of nodes in the tree.
Space Complexity: O(N) for the queue.
:
Solution Code
class Solution {
public TreeNode replaceCousins(TreeNode root) {
if (root == null) {
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
Map<TreeNode, Integer> parentMap = new HashMap<>();
Map<Integer, Integer> cousinsSumMap = new HashMap<>();
for (int i = 0; i < size; i++) {
TreeNode current = queue.poll();
TreeNode parent = parentMap.getOrDefault(current, null);
if (parent != null && parentMap.get(parent) != parentMap.get(current)) {
cousinsSumMap.put(parentMap.get(current), cousinsSumMap.getOrDefault(parentMap.get(current), 0) + current.val);
cousinsSumMap.put(parentMap.get(parent), cousinsSumMap.getOrDefault(parentMap.get(parent), 0) + current.val);
}
if (current.left != null) {
queue.offer(current.left);
parentMap.put(current.left, current);
}
if (current.right != null) {
queue.offer(current.right);
parentMap.put(current.right, current);
}
}
for (Map.Entry<Integer, Integer> entry : cousinsSumMap.entrySet()) {
for (Map.Entry<TreeNode, Integer> nodeEntry : parentMap.entrySet()) {
if (nodeEntry.getValue() == entry.getKey()) {
nodeEntry.getKey().val = entry.getValue();
}
}
}
}
return root;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2641 (Cousins in Binary Tree II)?
This page provides optimized solutions for LeetCode problem 2641 (Cousins in Binary Tree II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2641 (Cousins in Binary Tree II)?
The time complexity for LeetCode 2641 (Cousins in Binary Tree II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2641 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2641 in Java, C++, or Python.