A Sum tree of a binary tree is defined as a tree in which each node stores the sum of the values of all its left and right subtrees in the original tree. Additionally, the leaf nodes of the binary tree are replaced by zero in the Sum tree.
classSolution {
publicvoidconvertToSumTree(TreeNode root) {
helper(root);
}
privateinthelper(TreeNode node) {
// Base case: If the node is null, return 0if (node ==null) {
return 0;
}
// Recursive calls to left and right subtreesint leftSum = helper(node.left);
int rightSum = helper(node.right);
// Save the original value of the nodeint originalValue = node.value;
// Update node's value to the sum of left and right subtrees node.value= leftSum + rightSum;
// Return the total sum of subtree including original valuereturn originalValue + node.value;
}
// Example usagepublicstaticvoidmain(String[] args) {
TreeNode root =new TreeNode(10);
root.left=new TreeNode(2);
root.right=new TreeNode(6);
root.left.left=new TreeNode(1);
root.left.right=new TreeNode(3);
root.right.left=new TreeNode(4);
root.right.right=new TreeNode(5);
Solution solution =new Solution();
solution.convertToSumTree(root);
}
}
classSolution:
defconvertToSumTree(self, root):
defhelper(node):
# Base case: If the node is null, return 0if node isNone:
return0# Recursive calls to left and right subtrees left_sum = helper(node.left)
right_sum = helper(node.right)
# Save the original value of the node original_value = node.value
# Update node's value to the sum of left and right subtrees node.value = left_sum + right_sum
# Return the total sum of subtree including original valuereturn original_value + node.value
helper(root)
# Example usageroot = TreeNode(10, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(4), TreeNode(5)))
solution = Solution()
solution.convertToSumTree(root)
⏰ Time complexity: O(n), where n is the number of nodes in the binary tree. The algorithm involves visiting each node exactly once in postorder traversal.
🧺 Space complexity: O(h), where h is the height of the tree. The space complexity is proportional to the recursion stack depth.