Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
Last Updated :
30 Apr, 2024
Question: Given an arbitrary binary tree, convert it to a binary tree that holds Children Sum Property. You can only increment data values in any node (You cannot change the structure of the tree and cannot decrement the value of any node).
For example, the below tree doesn’t hold the children sum property, convert it to a tree that holds the property.
50
/ \
/ \
7 2
/ \ /\
/ \ / \
3 5 1 30
Algorithm: Traverse the given tree in post order to convert it, i.e., first change left and right children to hold the children sum property then change the parent node.
Let difference between node’s data and children sum be diff.
diff = node’s children sum - node’s data
If diff is 0 then nothing needs to be done.
If diff > 0 ( node’s data is smaller than node’s children sum) increment the node’s data by diff.
If diff < 0 (node’s data is greater than the node’s children sum) then increment one child’s data. We can choose to increment either left or right child if they both are not NULL. Let us always first increment the left child. Incrementing a child changes the subtree’s children sum property so we need to change left subtree also. So we recursively increment the left child. If left child is empty then we recursively call increment() for right child.
Let us run the algorithm for the given example.
First convert the left subtree (increment 7 to 8).
50
/ \
/ \
8 2
/ \ /\
/ \ / \
3 5 1 30
Then convert the right subtree (increment 2 to 31)
50
/ \
/ \
8 31
/ \ / \
/ \ / \
3 5 1 30
Now convert the root, we have to increment left subtree for converting the root.
50
/ \
/ \
19 31
/ \ / \
/ \ / \
14 5 1 30
Please note the last step – we have incremented 8 to 19, and to fix the subtree we have incremented 3 to 14.
Implementation:
C++
/* C++ Program to convert an arbitrary
binary tree to a tree that hold
children sum property */
#include<bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node* left;
node* right;
/* Constructor that allocates a new node
with the given data and NULL left and right
pointers. */
node(int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
/* This function is used
to increment left subtree */
void increment(node* node, int diff);
/* This function changes a tree
to hold children sum property */
void convertTree(node* node)
{
int left_data = 0, right_data = 0, diff;
/* If tree is empty or it's a leaf
node then return true */
if (node == NULL || (node->left == NULL &&
node->right == NULL))
return;
else
{
/* convert left and right subtrees */
convertTree(node->left);
convertTree(node->right);
/* If left child is not present then 0 is used
as data of left child */
if (node->left != NULL)
left_data = node->left->data;
/* If right child is not present then 0 is used
as data of right child */
if (node->right != NULL)
right_data = node->right->data;
/* get the diff of node's data and children sum */
diff = left_data + right_data - node->data;
/* If node's children sum is
greater than the node's data */
if (diff > 0)
node->data = node->data + diff;
/* THIS IS TRICKY --> If node's data
is greater than children sum,
then increment subtree by diff */
if (diff < 0)
increment(node, -diff); // -diff is used to make diff positive
}
}
/* This function is used
to increment subtree by diff */
void increment(node* node, int diff)
{
/* IF left child is not
NULL then increment it */
if(node->left != NULL)
{
node->left->data = node->left->data + diff;
// Recursively call to fix
// the descendants of node->left
increment(node->left, diff);
}
else if (node->right != NULL) // Else increment right child
{
node->right->data = node->right->data + diff;
// Recursively call to fix
// the descendants of node->right
increment(node->right, diff);
}
}
/* Given a binary tree,
printInorder() prints out its
inorder traversal*/
void printInorder(node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
cout<<node->data<<" ";
/* now recur on right child */
printInorder(node->right);
}
/* Driver code */
int main()
{
node *root = new node(50);
root->left = new node(7);
root->right = new node(2);
root->left->left = new node(3);
root->left->right = new node(5);
root->right->left = new node(1);
root->right->right = new node(30);
cout << "\nInorder traversal before conversion: " << endl;
printInorder(root);
convertTree(root);
cout << "\nInorder traversal after conversion: " << endl;
printInorder(root);
return 0;
}
// This code is contributed by rathbhupendra
Java
class Node {
int data;
Node left;
Node right;
Node(int val) {
data = val;
left = null;
right = null;
}
}
class Solution {
// Function to convert the binary tree to the Children Sum Property
public void convertToChildrenSumProperty(Node root) {
convertToChildrenSumPropertyUtil(root);
}
// Recursive helper function to convert the binary tree
private int convertToChildrenSumPropertyUtil(Node root) {
// Base case: if the current node is null, return 0
if (root == null) return 0;
// Recursively convert the left and right subtrees
int leftSum = convertToChildrenSumPropertyUtil(root.left);
int rightSum = convertToChildrenSumPropertyUtil(root.right);
// Calculate the current sum of the children
int currentSum = leftSum + rightSum;
// Calculate the difference between the current node's data and the sum of its children
int difference = currentSum - root.data;
// If the difference is positive, increment the current node's data
if (difference > 0) {
root.data += difference;
}
// If the difference is negative, decrement the left or right child's data
else if (root.left != null) {
root.left.data -= difference;
convertToChildrenSumPropertyUtil(root.left);
} else if (root.right != null) {
root.right.data -= difference;
convertToChildrenSumPropertyUtil(root.right);
}
// Return the updated data of the current node
return root.data;
}
// Function to perform an inorder traversal of the binary tree
public void inorderTraversal(Node root) {
if (root == null) return;
inorderTraversal(root.left);
System.out.print(root.data + " ");
inorderTraversal(root.right);
}
public static void main(String[] args) {
// Create the example binary tree
Node root = new Node(50);
root.left = new Node(7);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(1);
root.right.right = new Node(30);
Solution solution = new Solution();
System.out.println("Inorder traversal before conversion:");
solution.inorderTraversal(root);
System.out.println();
System.out.println();
solution.convertToChildrenSumProperty(root);
System.out.println("Inorder traversal after conversion:");
solution.inorderTraversal(root);
System.out.println();
}
}
Python3
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def convert_to_children_sum_property(root):
"""
Wrapper function to convert the entire binary tree to the Children Sum Property.
"""
convert_to_children_sum_property_util(root)
def convert_to_children_sum_property_util(root):
"""
Recursive function to convert the binary tree to the Children Sum Property.
"""
if not root:
return 0
# Recursively convert the left and right subtrees
left_sum = convert_to_children_sum_property_util(root.left)
right_sum = convert_to_children_sum_property_util(root.right)
# Calculate the current sum of the children
current_sum = left_sum + right_sum
# Calculate the difference between the current node's data and the sum of its children
difference = current_sum - root.data
# If the difference is positive, increment the current node's data
if difference > 0:
root.data += difference
# If the difference is negative, decrement the left or right child's data
elif root.left:
root.left.data -= difference
convert_to_children_sum_property_util(root.left)
elif root.right:
root.right.data -= difference
convert_to_children_sum_property_util(root.right)
# Return the updated data of the current node
return root.data
def inorder_traversal(root):
"""
Function to perform an inorder traversal of the binary tree.
"""
if not root:
return
inorder_traversal(root.left)
print(root.data, end=" ")
inorder_traversal(root.right)
if __name__ == "__main__":
# Create the example binary tree
root = Node(50)
root.left = Node(7)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right.left = Node(1)
root.right.right = Node(30)
print("Inorder traversal before conversion:")
inorder_traversal(root)
print()
print()
convert_to_children_sum_property(root)
print("Inorder traversal after conversion:")
inorder_traversal(root)
print()
C#
using System;
public class Node
{
public int data;
public Node left;
public Node right;
public Node(int val)
{
data = val;
left = null;
right = null;
}
}
public class Solution
{
// Function to convert the binary tree to the Children Sum Property
public void ConvertToChildrenSumProperty(Node root)
{
ConvertToChildrenSumPropertyUtil(root);
}
// Recursive helper function to convert the binary tree
private int ConvertToChildrenSumPropertyUtil(Node root)
{
// Base case: if the current node is null, return 0
if (root == null) return 0;
// Recursively convert the left and right subtrees
int leftSum = ConvertToChildrenSumPropertyUtil(root.left);
int rightSum = ConvertToChildrenSumPropertyUtil(root.right);
// Calculate the current sum of the children
int currentSum = leftSum + rightSum;
// Calculate the difference between the current node's data and the sum of its children
int difference = currentSum - root.data;
// If the difference is positive, increment the current node's data
if (difference > 0)
{
root.data += difference;
}
// If the difference is negative, decrement the left or right child's data
else if (root.left != null)
{
root.left.data -= difference;
ConvertToChildrenSumPropertyUtil(root.left);
}
else if (root.right != null)
{
root.right.data -= difference;
ConvertToChildrenSumPropertyUtil(root.right);
}
// Return the updated data of the current node
return root.data;
}
// Function to perform an inorder traversal of the binary tree
public void InorderTraversal(Node root)
{
if (root == null) return;
InorderTraversal(root.left);
Console.Write(root.data + " ");
InorderTraversal(root.right);
}
public static void Main(string[] args)
{
// Create the example binary tree
Node root = new Node(50);
root.left = new Node(7);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(1);
root.right.right = new Node(30);
Solution solution = new Solution();
Console.WriteLine("Inorder traversal before conversion:");
solution.InorderTraversal(root);
Console.WriteLine();
Console.WriteLine();
solution.ConvertToChildrenSumProperty(root);
Console.WriteLine("Inorder traversal after conversion:");
solution.InorderTraversal(root);
Console.WriteLine();
}
}
Javascript
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Recursive function to convert the binary tree to the Children Sum Property
function convertToChildrenSumPropertyUtil(root) {
// Base case: if the current node is null, return 0
if (!root) return 0;
// Recursively convert the left and right subtrees
let leftSum = convertToChildrenSumPropertyUtil(root.left);
let rightSum = convertToChildrenSumPropertyUtil(root.right);
// Calculate the current sum of the children
let currentSum = leftSum + rightSum;
// Calculate the difference between the current node's data and the sum of its children
let difference = currentSum - root.data;
// If the difference is positive, increment the current node's data
if (difference > 0) {
root.data += difference;
}
// If the difference is negative, decrement the left or right child's data
else if (root.left) {
root.left.data -= difference;
convertToChildrenSumPropertyUtil(root.left);
} else if (root.right) {
root.right.data -= difference;
convertToChildrenSumPropertyUtil(root.right);
}
// Return the updated data of the current node
return root.data;
}
// Wrapper function to convert the entire binary tree to the Children Sum Property
function convertToChildrenSumProperty(root) {
convertToChildrenSumPropertyUtil(root);
}
// Function to perform an inorder traversal of the binary tree
function inorderTraversal(root) {
if (!root) return;
inorderTraversal(root.left);
console.log(root.data, " ");
inorderTraversal(root.right);
}
// Create the example binary tree
let root = new Node(50);
root.left = new Node(7);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(1);
root.right.right = new Node(30);
console.log("Inorder traversal before conversion:");
inorderTraversal(root);
console.log();
console.log();
convertToChildrenSumProperty(root);
console.log("Inorder traversal after conversion:");
inorderTraversal(root);
console.log();
OutputInorder traversal before conversion:
3 7 5 50 1 2 30
Inorder traversal after conversion:
14 19 5 50 1 31 30
Time Complexity: O(n^2), Worst case complexity is for a skewed tree such that nodes are in decreasing order from root to leaf.
Space Complexity: O(h) where h is the height of the binary tree.
Please write comments if you find any bug in the above algorithm or a better way to solve the same problem.
METHOD-2: Most Optimized Solution: (Linear Time)
The idea is to fix the children in top-down fashion of Tree,
and fix the children sum property in bottom-up fashion of Tree
Algorithm:
50
/ \
/ \
7 2
/ \ /\
/ \ / \
3 5 1 30
Here, the issue is having shortage while summing, eg – 1+30 =31 then 3+5 = 8 => 31+8 =39, but u cannot decrement 50 to 39 as per rule.
So while going down the tree increase the value so to make sure we don’t end up with shortage.
Then all we need to do is, while returning, just sum the children and replace the parent node.
At last, the Children sum property holds TRUE. (As there is no restriction on the value needs to be minimum as such)
CODE:
C++
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
int convertToChildrenSumProperty(Node* root, int& difference) {
if (!root) return 0;
int leftSum = convertToChildrenSumProperty(root->left, difference);
int rightSum = convertToChildrenSumProperty(root->right, difference);
int currentSum = leftSum + rightSum;
difference = currentSum - root->data;
if (difference > 0) {
root->data += difference;
} else if (root->left) {
root->left->data -= difference;
convertToChildrenSumProperty(root->left, difference);
} else if (root->right) {
root->right->data -= difference;
convertToChildrenSumProperty(root->right, difference);
}
return root->data;
}
void convertToChildrenSumTree(Node* root) {
int difference = 0;
convertToChildrenSumProperty(root, difference);
}
void inorderTraversal(Node* root) {
if (!root) return;
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
int main() {
// Create the example binary tree
Node* root = new Node(50);
root->left = new Node(7);
root->right = new Node(2);
root->left->left = new Node(3);
root->left->right = new Node(5);
root->right->left = new Node(1);
root->right->right = new Node(30);
cout << "Inorder traversal before conversion: " << endl;
inorderTraversal(root);
cout << endl << endl;
convertToChildrenSumTree(root);
cout << "Inorder traversal after conversion: " << endl;
inorderTraversal(root);
cout << endl;
return 0;
}
Java
// Java code for the above approach
import java.io.*;
// Java code to convert a given binary tree to
// a tree where every node contains sum of all nodes
// in left and right subtree in the original tree
class Node {
int data;
Node left, right;
Node(int data)
{
this.data = data;
left = right = null;
}
}
class BinaryTree {
Node root;
// method to print the inorder traversal of
// the binary tree
void printInorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.data + " ");
/* now recur on right child */
printInorder(node.right);
}
// method to convert the binary tree
void convertTree(Node root)
{
if (root == null)
return;
int childSum = 0;
// sum of children's data
if (root.left != null)
childSum += root.left.data;
if (root.right != null)
childSum += root.right.data;
// if children sum is greater than root
if (childSum >= root.data) {
root.data = childSum;
}
else {
// if children sum is less than root
// change both children
if (root.left != null)
root.left.data = root.data;
if (root.right != null)
root.right.data = root.data;
}
// now go down the tree and check others - Inorder
convertTree(root.left);
convertTree(root.right);
// here is the backtracking part happens, as changes
// may happen
int totVal = 0;
if (root.left != null)
totVal += root.left.data;
if (root.right != null)
totVal += root.right.data;
// Leaf node dont update, as it will make it 0
if (root.left != null || root.right != null)
root.data = totVal;
// So that at last the children Sum property stays
// TRUE
}
/* Driver code */
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(50);
tree.root.left = new Node(7);
tree.root.right = new Node(2);
tree.root.left.left = new Node(3);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(1);
tree.root.right.right = new Node(30);
System.out.print(
"Inorder traversal before conversion: ");
tree.printInorder(tree.root);
tree.convertTree(tree.root);
System.out.print(
"\nInorder traversal after conversion: ");
tree.printInorder(tree.root);
}
}
// This code is contributed by lokeshpotta20.
Python3
#Python code for the above approach
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printInorder(node):
if node is None:
return
# first recur on left child
printInorder(node.left)
# then print the data of node
print(node.data, end=" ")
# now recur on right child
printInorder(node.right)
def convertTree(root):
if root is None:
return
childSum = 0
if root.left:
childSum += root.left.data
if root.right:
childSum += root.right.data
if childSum >= root.data:
# change root
root.data = childSum
else:
# change both children
if root.left:
root.left.data = root.data
if root.right:
root.right.data = root.data
# now go down the tree and check others - Inorder
convertTree(root.left)
convertTree(root.right)
# here is the backtracking part happens, as changes may happen
totVal = 0
if root.left:
totVal += root.left.data
if root.right:
totVal += root.right.data
# Leaf node dont update, as it will make it 0
if root.left or root.right:
root.data = totVal
# So that at last the children Sum property stays TRUE
# Driver code
if __name__ == "__main__":
root = Node(50)
root.left = Node(7)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right.left = Node(1)
root.right.right = Node(30)
print("Inorder traversal before conversion: ")
printInorder(root)
convertTree(root)
print("\nInorder traversal after conversion: ")
printInorder(root)
C#
// C# program to convert an arbitrary
// binary tree to a tree that holds
// children sum property
using System;
// A binary tree node
public class node{
public int data;
public node left, right;
public node(int item){
data = item;
left = right = null;
}
}
class GFG{
public node root;
/* This function changes a tree to
hold children sum property */
public virtual void convertTree(node root){
if(root == null) return;
int childSum = 0;
if(root.left != null) childSum += root.left.data;
if(root.right != null) childSum += root.right.data;
if(childSum >= root.data){
// change root
root.data = childSum;
}else{
// change both children
if(root.left != null) root.left.data = root.data;
if(root.right != null) root.right.data = root.data;
}
// now go down the tree and check others - Inorder
convertTree(root.left);
convertTree(root.right);
// here is the backtracking part happens, as changes may happend
int totVal = 0;
if(root.left != null) totVal += root.left.data;
if(root.right != null) totVal += root.right.data;
// Leaf node don't update, as it will make it 0
if(root.left != null || root.right != null) root.data = totVal;
// so that at last the children sum property syas true
}
public virtual void printInorder(node node){
if (node == null) return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
Console.Write(node.data + " ");
/* now recur on right child */
printInorder(node.right);
}
// Driver Code
public static void Main(string[] args){
GFG tree = new GFG();
tree.root = new node(50);
tree.root.left = new node(7);
tree.root.right = new node(2);
tree.root.left.left = new node(3);
tree.root.left.right = new node(5);
tree.root.right.left = new node(1);
tree.root.right.right = new node(30);
Console.WriteLine("Inorder traversal before conversion is :");
tree.printInorder(tree.root);
tree.convertTree(tree.root);
Console.WriteLine("");
Console.WriteLine("Inorder traversal after conversion is :");
tree.printInorder(tree.root);
}
}
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)
Javascript
// JavaScript program for the above approach
class node{
constructor(data){
this.data = data;
this.left = null;
this.right = null;
}
}
// function to print inorder traversal of binary tree
function printInorder(node)
{
if(node == null) return;
// first recur on left child
printInorder(node.left);
// then print the data of node
console.log(node.data + " ");
// now recur on right child
printInorder(node.right);
}
function convertTree(root){
if(root == null) return null;
let childSum = 0;
if(root.left != null) childSum += root.left.data;
if(root.right != null) childSum += root.right.data;
if(childSum >= root.data){
// change root
root.data = childSum;
}else{
// change both children
if(root.left) root.left.data = root.data;
if(root.right) root.right.data = root.data;
}
// now go down the tree and check others - Inorder
convertTree(root.left);
convertTree(root.right);
// here is the backtracking part happens, as changes may happen
let totVal = 0;
if(root.left) totVal += root.left.data;
if(root.right) totVal += root.right.data;
// Leaf node dont update, as it will make it 0
if(root.left || root.right) root.data = totVal;
//So that at last the children Sum property stays TRUE
}
// driver code to test above function
let root = new node(50);
root.left = new node(7);
root.right = new node(2);
root.left.left = new node(3);
root.left.right = new node(5);
root.right.left = new node(1);
root.right.right = new node(30);
console.log("Inorder Traversal before conversion: ");
printInorder(root);
convertTree(root);
console.log("Inorder Traversal after conversion: ");
printInorder(root);
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
OutputInorder traversal before conversion:
3 7 5 50 1 2 30
Inorder traversal after conversion:
50 100 50 200 50 100 50
Time Complexity: O(n) as we are doing traversal of the tree only once.
Reason :
Recurrence Relation : T(n) = 2*T(n/2) + O(1)
Space Complexity: O(ht of tree) best and avg: O(log n ) worst: O(n) Skewed trees.
Reason:
Function call stack of recursion.
Approach using DP:
In this implementation, a queue is used to perform a level-order traversal of the tree. The queue helps to process each node and its children in a breadth-first manner. The program calculates the difference between the sum of the left and right child values and the current node’s value. If the difference is positive, the current node’s value is increased by the difference. If the difference is negative, the program distributes the difference to the left or right child, depending on which child is present.
Here’s the implementation of the given program using a dynamic programming (DP) approach:
C++
#include <iostream>
#include <vector>
class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int val) : data(val), left(nullptr), right(nullptr) {}
};
// Function to increment the subtree by a given difference
void increment(TreeNode* node, int diff) {
if (node->left != nullptr) {
node->left->data += diff;
increment(node->left, diff);
} else if (node->right != nullptr) {
node->right->data += diff;
increment(node->right, diff);
}
}
// Function to convert the tree to hold the children sum property
void convertTree(TreeNode* node) {
if (node == nullptr || (node->left == nullptr && node->right == nullptr)) {
return;
}
// Recursively convert left and right subtrees
convertTree(node->left);
convertTree(node->right);
// Calculate the sum of data in left and right subtrees
int left_data = (node->left != nullptr) ? node->left->data : 0;
int right_data = (node->right != nullptr) ? node->right->data : 0;
// Calculate the difference between node's data and children sum
int diff = left_data + right_data - node->data;
// Adjust node's data based on the difference
if (diff > 0) {
node->data += diff;
} else if (diff < 0) {
increment(node, -diff); // Make diff positive for incrementing
}
}
// Function to print the inorder traversal of the tree
void printInorder(TreeNode* node) {
if (node == nullptr) {
return;
}
printInorder(node->left);
std::cout << node->data << " ";
printInorder(node->right);
}
int main() {
// Create a sample binary tree
TreeNode* root = new TreeNode(50);
root->left = new TreeNode(7);
root->right = new TreeNode(2);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(1);
root->right->right = new TreeNode(30);
// Print the original tree
std::cout << "Inorder traversal before conversion:" << std::endl;
printInorder(root);
// Convert the tree to hold children sum property
convertTree(root);
// Print the modified tree
std::cout << "\nInorder traversal after conversion:" << std::endl;
printInorder(root);
// Clean up memory (optional)
// ...
return 0;
}
Java
class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode(int val) {
data = val;
left = null;
right = null;
}
}
public class Main {
static void increment(TreeNode node, int diff) {
if (node.left != null) {
node.left.data += diff;
increment(node.left, diff);
} else if (node.right != null) {
node.right.data += diff;
increment(node.right, diff);
}
}
static void convertTree(TreeNode node) {
if (node == null || (node.left == null && node.right == null)) {
return;
}
convertTree(node.left);
convertTree(node.right);
int left_data = (node.left != null) ? node.left.data : 0;
int right_data = (node.right != null) ? node.right.data : 0;
int diff = left_data + right_data - node.data;
if (diff > 0) {
node.data += diff;
} else if (diff < 0) {
increment(node, -diff);
}
}
static void printInorder(TreeNode node) {
if (node == null) {
return;
}
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(50);
root.left = new TreeNode(7);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(1);
root.right.right = new TreeNode(30);
System.out.println("Inorder traversal before conversion:");
printInorder(root);
convertTree(root);
System.out.println("\nInorder traversal after conversion:");
printInorder(root);
}
}
Python3
class TreeNode:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def increment(node, diff):
if node.left is not None:
node.left.data += diff
increment(node.left, diff)
elif node.right is not None:
node.right.data += diff
increment(node.right, diff)
def convertTree(node):
if node is None or (node.left is None and node.right is None):
return
convertTree(node.left)
convertTree(node.right)
left_data = node.left.data if node.left is not None else 0
right_data = node.right.data if node.right is not None else 0
diff = left_data + right_data - node.data
if diff > 0:
node.data += diff
elif diff < 0:
increment(node, -diff)
def printInorder(node):
if node is None:
return
printInorder(node.left)
print(node.data, end=" ")
printInorder(node.right)
root = TreeNode(50)
root.left = TreeNode(7)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(5)
root.right.left = TreeNode(1)
root.right.right = TreeNode(30)
print("Inorder traversal before conversion:")
printInorder(root)
convertTree(root)
print("\nInorder traversal after conversion:")
printInorder(root)
C#
using System;
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
data = val;
left = null;
right = null;
}
}
public class MainClass {
static void Increment(TreeNode node, int diff) {
if (node.left != null) {
node.left.data += diff;
Increment(node.left, diff);
} else if (node.right != null) {
node.right.data += diff;
Increment(node.right, diff);
}
}
static void ConvertTree(TreeNode node) {
if (node == null || (node.left == null && node.right == null)) {
return;
}
ConvertTree(node.left);
ConvertTree(node.right);
int left_data = (node.left != null) ? node.left.data : 0;
int right_data = (node.right != null) ? node.right.data : 0;
int diff = left_data + right_data - node.data;
if (diff > 0) {
node.data += diff;
} else if (diff < 0) {
Increment(node, -diff);
}
}
static void PrintInorder(TreeNode node) {
if (node == null) {
return;
}
PrintInorder(node.left);
Console.Write(node.data + " ");
PrintInorder(node.right);
}
public static void Main (string[] args) {
TreeNode root = new TreeNode(50);
root.left = new TreeNode(7);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(1);
root.right.right = new TreeNode(30);
Console.WriteLine("Inorder traversal before conversion:");
PrintInorder(root);
ConvertTree(root);
Console.WriteLine("\nInorder traversal after conversion:");
PrintInorder(root);
}
}
Javascript
class TreeNode {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
function increment(node, diff) {
if (node.left !== null) {
node.left.data += diff;
increment(node.left, diff);
} else if (node.right !== null) {
node.right.data += diff;
increment(node.right, diff);
}
}
function convertTree(node) {
if (node === null || (node.left === null && node.right === null)) {
return;
}
convertTree(node.left);
convertTree(node.right);
const left_data = (node.left !== null) ? node.left.data : 0;
const right_data = (node.right !== null) ? node.right.data : 0;
const diff = left_data + right_data - node.data;
if (diff > 0) {
node.data += diff;
} else if (diff < 0) {
increment(node, -diff);
}
}
function printInorder(node) {
if (node === null) {
return;
}
printInorder(node.left);
process.stdout.write(node.data + " ");
printInorder(node.right);
}
const root = new TreeNode(50);
root.left = new TreeNode(7);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(1);
root.right.right = new TreeNode(30);
console.log("Inorder traversal before conversion:");
printInorder(root);
convertTree(root);
console.log("\nInorder traversal after conversion:");
printInorder(root
OutputInorder traversal before conversion:
3 7 5 50 1 2 30
Inorder traversal after conversion:
14 19 5 50 1 31 30
Time Complexity: O(n)
Space Complexity: O(n)
The above Method-2 Idea, Algorithm, and Code are contributed by Balakrishnan R (rbkraj000 – GFG ID).
Share your thoughts in the comments
Please Login to comment...