Open In App

Convert an arbitrary Binary Tree to a tree that holds Children Sum Property – Set 2

Last Updated : 21 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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’s sum property, convert it to a tree that holds the property.

             50

           /     \     

         /         \

       7             2

     / \             /\

   /     \          /   \

  3        5      1      30

 

Naive Approach: The Naive Approach is discussed in the Set 1 of this article. Here, we are discussing the optimized approach.

Algorithm: Convert the children to the maximum possible value so while moving back there will be no parent having more value than the children, so there will be no extra function to again traverse the subtrees from that node.

  • If the sum of children is less than current node, replace the value of both children with current node’s value.

if(node->left + node->right < node->data) 
             put node->data value in both the child

  • If the sum of children is greater than or equal to current node, replace the value of current node’s value with sum of children.

if(node->left->data + node->right->data >= node->data) 
             put summation of both child data values in node->data

  • While traversing back overwrite the existing node values with the sum of left and right child data.

(Note: there will not be any case where the value of node will be greater than the sum of values of their child, because we have given them the maximum possible value).

Follow the steps below to solve the problem:

  • If root is null then return.
  • Initialize the variable childSum as 0.
  • If root has children, then add their value to childSum.
  • If childSum is greater than equal to root->data, then set root->data as childSum.
  • Else, if there are children of root, then set their children’s data as root->data.
  • Call the same function for root->left and root->right.
  • Initialize the variable totalSumToChangeParent as 0.
  • If root has children, then add the value of their data to the variable totalSumToChangeParent.
  • If there is any child of root, then set the value of root as totalSumToChangeParent.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a node in a binary tree
struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int x)
    {
        data = x;
        left = NULL;
        right = NULL;
    }
};
 
// Convert the tree such that it holds
// children sum property
void convertTree(Node* root)
{
    if (root == NULL)
        return;
 
    // Calculating the sum
    // of left and right child
    int childSum = 0;
    if (root->left)
        childSum += root->left->data;
    if (root->right)
        childSum += root->right->data;
 
    // If sum of child is greater
    // then change the node's
    // data else change the data
    // of left and right child to
    // make sure they will get
    // the maximum possible value
    if (childSum >= root->data)
        root->data = childSum;
    else {
        if (root->left)
            root->left->data = root->data;
        if (root->right)
            root->right->data = root->data;
    }
 
    // Recursive call for left child
    convertTree(root->left);
 
    // Recursive call for right child
    convertTree(root->right);
 
    // Overwriting the parent's data
    int totalSumToChangeParent = 0;
    if (root->left)
        totalSumToChangeParent
            += root->left->data;
    if (root->right)
        totalSumToChangeParent
            += root->right->data;
    if (root->left || root->right)
        root->data = totalSumToChangeParent;
}
 
void printInorder(Node* root)
{
    if (root == NULL)
        return;
 
    // Recursive call to left child
    printInorder(root->left);
 
    // Printing the node's data
    cout << root->data << " ";
 
    // Recursive call to right child
    printInorder(root->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);
 
    convertTree(root);
 
    printInorder(root);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Structure of a node in a binary tree
static class Node {
    int data;
    Node left;
    Node right;
    Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
};
 
// Convert the tree such that it holds
// children sum property
static void convertTree(Node root)
{
    if (root == null)
        return;
 
    // Calculating the sum
    // of left and right child
    int childSum = 0;
    if (root.left!=null)
        childSum += root.left.data;
    if (root.right!=null)
        childSum += root.right.data;
 
    // If sum of child is greater
    // then change the node's
    // data else change the data
    // of left and right child to
    // make sure they will get
    // the maximum possible value
    if (childSum >= root.data)
        root.data = childSum;
    else {
        if (root.left!=null)
            root.left.data = root.data;
        if (root.right!=null)
            root.right.data = root.data;
    }
 
    // Recursive call for left child
    convertTree(root.left);
 
    // Recursive call for right child
    convertTree(root.right);
 
    // Overwriting the parent's data
    int totalSumToChangeParent = 0;
    if (root.left != null)
        totalSumToChangeParent
            += root.left.data;
    if (root.right != null)
        totalSumToChangeParent
            += root.right.data;
    if (root.left != null || root.right != null)
        root.data = totalSumToChangeParent;
}
 
static void printInorder(Node root)
{
    if (root == null)
        return;
 
    // Recursive call to left child
    printInorder(root.left);
 
    // Printing the node's data
    System.out.print(root.data+ " ");
 
    // Recursive call to right child
    printInorder(root.right);
}
 
// Driver Code
public static void main(String[] args)
{
 
    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);
 
    convertTree(root);
 
    printInorder(root);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python code for the above approach
 
# Class of a node in a binary tree
class Node:
 
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
 
# Convert the tree such that it holds
# children sum property
def convertTree(root):
    if (root == None):
        return
 
    # Calculating the sum
    # of left and right child
    childSum = 0
    if (root.left):
        childSum += root.left.data
    if (root.right):
        childSum += root.right.data
 
    # If sum of child is greater
    # then change the node's
    # data else change the data
    # of left and right child to
    # make sure they will get
    # the maximum possible value
    if (childSum >= root.data):
        root.data = childSum
    else:
        if (root.left):
            root.left.data = root.data
        if (root.right):
            root.right.data = root.data
 
    # Recursive call for left child
    convertTree(root.left)
 
    # Recursive call for right child
    convertTree(root.right)
 
    # Overwriting the parent's data
    totalSumToChangeParent = 0
    if (root.left):
        totalSumToChangeParent += root.left.data
    if (root.right):
        totalSumToChangeParent += root.right.data
    if (root.left or root.right):
        root.data = totalSumToChangeParent
 
 
def printInorder(root):
    if (root == None):
        return
 
    # Recursive call to left child
    printInorder(root.left)
 
    # Printing the node's data
    print(root.data, end=" ")
 
    # Recursive call to right child
    printInorder(root.right)
 
# Driver Code
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)
 
convertTree(root)
 
printInorder(root)
 
# self code is contributed by Saurabh Jaiswal


C#




// C# program for the above approach
using System;
public class GFG{
 
// Structure of a node in a binary tree
class Node {
    public int data;
    public Node left;
    public Node right;
    public Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
};
 
// Convert the tree such that it holds
// children sum property
static void convertTree(Node root)
{
    if (root == null)
        return;
 
    // Calculating the sum
    // of left and right child
    int childSum = 0;
    if (root.left!=null)
        childSum += root.left.data;
    if (root.right!=null)
        childSum += root.right.data;
 
    // If sum of child is greater
    // then change the node's
    // data else change the data
    // of left and right child to
    // make sure they will get
    // the maximum possible value
    if (childSum >= root.data)
        root.data = childSum;
    else {
        if (root.left!=null)
            root.left.data = root.data;
        if (root.right!=null)
            root.right.data = root.data;
    }
 
    // Recursive call for left child
    convertTree(root.left);
 
    // Recursive call for right child
    convertTree(root.right);
 
    // Overwriting the parent's data
    int totalSumToChangeParent = 0;
    if (root.left != null)
        totalSumToChangeParent
            += root.left.data;
    if (root.right != null)
        totalSumToChangeParent
            += root.right.data;
    if (root.left != null || root.right != null)
        root.data = totalSumToChangeParent;
}
 
static void printInorder(Node root)
{
    if (root == null)
        return;
 
    // Recursive call to left child
    printInorder(root.left);
 
    // Printing the node's data
    Console.Write(root.data+ " ");
 
    // Recursive call to right child
    printInorder(root.right);
}
 
// Driver Code
public static void Main(String[] args)
{
 
    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);
 
    convertTree(root);
 
    printInorder(root);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
       // JavaScript code for the above approach
 
       // Class of a node in a binary tree
       class Node {
 
           constructor(x) {
               this.data = x;
               this.left = null;
               this.right = null;
           }
       };
 
       // Convert the tree such that it holds
       // children sum property
       function convertTree(root) {
           if (root == null)
               return;
 
           // Calculating the sum
           // of left and right child
           let childSum = 0;
           if (root.left)
               childSum += root.left.data;
           if (root.right)
               childSum += root.right.data;
 
           // If sum of child is greater
           // then change the node's
           // data else change the data
           // of left and right child to
           // make sure they will get
           // the maximum possible value
           if (childSum >= root.data)
               root.data = childSum;
           else {
               if (root.left)
                   root.left.data = root.data;
               if (root.right)
                   root.right.data = root.data;
           }
 
           // Recursive call for left child
           convertTree(root.left);
 
           // Recursive call for right child
           convertTree(root.right);
 
           // Overwriting the parent's data
           let totalSumToChangeParent = 0;
           if (root.left)
               totalSumToChangeParent
                   += root.left.data;
           if (root.right)
               totalSumToChangeParent
                   += root.right.data;
           if (root.left || root.right)
               root.data = totalSumToChangeParent;
       }
 
       function printInorder(root) {
           if (root == null)
               return;
 
           // Recursive call to left child
           printInorder(root.left);
 
           // Printing the node's data
           document.write(root.data + " ");
 
           // Recursive call to right child
           printInorder(root.right);
       }
 
       // Driver Code
       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);
 
       convertTree(root);
 
       printInorder(root);
 
 // This code is contributed by Potta Lokesh
   </script>


 
 

Output: 

50 100 50 200 50 100 50

 

 

Time Complexity: O(N) 
Auxiliary Space: O(N)

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads