Convert a Binary Tree into a Sum Tree
Problem and examples
| Input Tree | Level Order Output | Description |
|---|---|---|
| [10, -2, 6, 8, -4, null, 5] | [[13], [4, 5], [0, 0, 0]] | Standard tree: Converted to sum tree where each node is the sum of values in its left and right subtrees |
| [1] | [[0]] | Edge case: A single node becomes 0 as it has no children |
| [] | [] | Edge case: Empty tree |
| [5, 3, null, 2, null, null, null, 1] | [[6], [3], [1], [0]] | Deep left-skewed tree converted into a sum tree; each node is updated recursively |
| [7, null, 9, null, null, null, 11] | [[20], [11], [0]] | Right-skewed tree: Each node updated to sum of subtree |
How it works
Understanding the Problem
The task is to convert a given binary tree into a sum tree. In a sum tree, each node’s value is replaced by the sum of values of its left and right subtrees in the original tree. For leaf nodes, since they don’t have children, their value becomes 0.
This transformation is done recursively, which means for each node, we first compute the sum of its left and right subtrees and update the node’s value, then repeat the process for its children.
Step-by-Step Solution with Example
Step 1: Understand Tree Structure
Consider this example binary tree:
10
/ -2 6
/ / 8 -4 7 5
We need to convert this into a sum tree. For every node, we’ll replace its value with the sum of values in its left and right subtrees from the original tree.
Step 2: Process Leaf Nodes
Leaf nodes have no children, so their new value becomes 0.
- 8 → 0
- -4 → 0
- 7 → 0
- 5 → 0
Step 3: Process Intermediate Nodes
Now, we go one level up and calculate the new values based on the original values of children.
- -2 has children 8 and -4 → new value = 8 + (-4) = 4
- 6 has children 7 and 5 → new value = 7 + 5 = 12
Step 4: Process Root Node
Finally, we compute the value for the root node.
- 10 has children -2 and 6 → in original tree, their values were -2 and 6 → new value = -2 + 6 = 4
Step 5: Update Tree
After the transformation, the sum tree looks like this:
4
/ 4 12
/ / 0 0 0 0
Edge Cases
Case 1: Tree with Multiple Levels
This is the general case like the example above. Each internal node gets updated based on the sum of its children’s original values. Leaf nodes become 0.
Case 2: Tree with a Single Node
If the tree only has one node, there are no children to sum. Therefore, the single node becomes 0, since it's considered a leaf node.
Case 3: Empty Tree
If the input tree is empty (i.e., the root is null), then the output is also an empty tree or null. This is the base case in our recursion.
Finally
Converting a binary tree to a sum tree requires a post-order traversal, where we visit left and right children before updating the current node. The solution handles all edge cases and maintains correctness by updating nodes only after their subtrees are processed. Always remember to handle base cases like leaf nodes and empty trees to avoid runtime errors.
- If the tree is empty, return
0. - Recursively convert the left subtree into a sum tree and obtain its sum.
- Recursively convert the right subtree into a sum tree and obtain its sum.
- Store the current node's original value in a temporary variable, e.g.,
oldVal. - Update the current node's value to the sum of the left and right subtree sums.
- Return the sum of the updated node value and the original value (
node.val + oldVal) so it can be used by the parent node.
Implementation and efficiency
C implementation
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
int toSumTree(TreeNode* root) {
if (root == NULL) return 0;
int oldVal = root->val;
int leftSum = toSumTree(root->left);
int rightSum = toSumTree(root->right);
root->val = leftSum + rightSum;
return root->val + oldVal;
}
int main() {
TreeNode* root = createNode(10);
root->left = createNode(-2);
root->left->left = createNode(8);
root->left->right = createNode(-4);
root->right = createNode(6);
toSumTree(root);
printf("Root value after conversion: %d\n", root->val);
return 0;
}C++ implementation
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
};
int toSumTree(TreeNode* root) {
if (root == nullptr) return 0;
int oldVal = root->val;
int leftSum = toSumTree(root->left);
int rightSum = toSumTree(root->right);
root->val = leftSum + rightSum;
return root->val + oldVal;
}
int main() {
TreeNode* root = new TreeNode(10);
root->left = new TreeNode(-2);
root->left->left = new TreeNode(8);
root->left->right = new TreeNode(-4);
root->right = new TreeNode(6);
toSumTree(root);
cout << "Root value after conversion: " << root->val << endl;
return 0;
}Python implementation
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def to_sum_tree(root):
if root is None:
return 0
old_val = root.val
left_sum = to_sum_tree(root.left)
right_sum = to_sum_tree(root.right)
root.val = left_sum + right_sum
return root.val + old_val
if __name__ == '__main__':
root = TreeNode(10, TreeNode(-2, TreeNode(8), TreeNode(-4)), TreeNode(6))
to_sum_tree(root)
print("Root value after conversion:", root.val)Java implementation
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class SumTreeJava {
public int toSumTree(TreeNode root) {
if (root == null) return 0;
int oldVal = root.val;
int leftSum = toSumTree(root.left);
int rightSum = toSumTree(root.right);
root.val = leftSum + rightSum;
return root.val + oldVal;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(-2);
root.left.left = new TreeNode(8);
root.left.right = new TreeNode(-4);
root.right = new TreeNode(6);
SumTreeJava obj = new SumTreeJava();
obj.toSumTree(root);
System.out.println("Root value after conversion: " + root.val);
}
}JavaScript implementation
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function toSumTree(root) {
if (!root) return 0;
const oldVal = root.val;
const leftSum = toSumTree(root.left);
const rightSum = toSumTree(root.right);
root.val = leftSum + rightSum;
return root.val + oldVal;
}
const root = new TreeNode(10, new TreeNode(-2, new TreeNode(8), new TreeNode(-4)), new TreeNode(6));
toSumTree(root);
console.log("Root value after conversion:", root.val);Go implementation
package main
import (
"fmt"
)
type TreeNode struct {
val int
left *TreeNode
right *TreeNode
}
func toSumTree(root *TreeNode) int {
if root == nil {
return 0
}
oldVal := root.val
leftSum := toSumTree(root.left)
rightSum := toSumTree(root.right)
root.val = leftSum + rightSum
return root.val + oldVal
}
func main() {
root := &TreeNode{val: 10,
left: &TreeNode{val: -2, left: &TreeNode{val: 8}, right: &TreeNode{val: -4}},
right: &TreeNode{val: 6}}
toSumTree(root)
fmt.Println("Root value after conversion:", root.val)
}Rust implementation
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
impl TreeNode {
fn new(val: i32) -> Self {
TreeNode { val, left: None, right: None }
}
}
fn to_sum_tree(node: &mut Option<Box<TreeNode>>) -> i32 {
if let Some(ref mut n) = node {
let old_val = n.val;
let left_sum = to_sum_tree(&mut n.left);
let right_sum = to_sum_tree(&mut n.right);
n.val = left_sum + right_sum;
return n.val + old_val;
}
0
}
fn main() {
let mut root = Some(Box::new(TreeNode {
val: 10,
left: Some(Box::new(TreeNode {
val: -2,
left: Some(Box::new(TreeNode::new(8))),
right: Some(Box::new(TreeNode::new(-4)))
})),
right: Some(Box::new(TreeNode::new(6)))}));
to_sum_tree(&mut root);
if let Some(node) = root { println!("Root value after conversion: {}", node.val); }
}Kotlin implementation
class TreeNode(var val: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun toSumTree(root: TreeNode?): Int {
if (root == null) return 0
val oldVal = root.val
val leftSum = toSumTree(root.left)
val rightSum = toSumTree(root.right)
root.val = leftSum + rightSum
return root.val + oldVal
}
fun main() {
val root = TreeNode(10)
root.left = TreeNode(-2)
root.left?.left = TreeNode(8)
root.left?.right = TreeNode(-4)
root.right = TreeNode(6)
toSumTree(root)
println("Root value after conversion: ${root.val}")
}TypeScript implementation
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val: number, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function toSumTree(root: TreeNode | null): number {
if (root === null) return 0;
const oldVal = root.val;
const leftSum = toSumTree(root.left);
const rightSum = toSumTree(root.right);
root.val = leftSum + rightSum;
return root.val + oldVal;
}
const root = new TreeNode(10, new TreeNode(-2, new TreeNode(8), new TreeNode(-4)), new TreeNode(6));
toSumTree(root);
console.log("Root value after conversion:", root.val);