2641. Cousins in Binary Tree II
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.
:
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.