713144. Transform to Sum Tree
Easy
Transform to Sum Tree
Summary
Given a binary tree, transform it into a sum tree where each node's value is equal to the sum of all values in its subtree. This problem requires understanding of tree traversal and manipulation.
Detailed Explanation
The given binary tree can be transformed into a sum tree by performing a level order traversal (BFS) and updating the node values accordingly. The idea is to keep track of the sum of all nodes at each level and assign it to the root node of that level. This process continues until all levels are processed.
Here's a step-by-step breakdown:
- Initialize an empty queue
qand add the root node of the binary tree. - While
qis not empty, do the following:- Dequeue a node and calculate its sum by recursively summing up all nodes in its subtree.
- Assign this sum to the current node.
- Add the children of the current node to the queue if they exist.
- Return the transformed binary tree.
Time complexity: O(n), where n is the number of nodes in the binary tree, since we visit each node once. Space complexity: O(w), where w is the maximum width of the binary tree, due to the level order traversal.
Optimized Solutions
Java
class Node {
int val;
Node left, right;
public Node(int v) {
val = v;
}
}
public class TransformToSumTree {
public static Node transform(Node root) {
if (root == null) return null;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int sum = 0;
int levelSize = q.size();
for (int i = 0; i < levelSize; i++) {
Node node = q.poll();
sum += node.val;
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(node.right);
}
root.val = sum;
}
return root;
}
}