Open In App

Replace each node by the sum of all nodes in the same level of a Binary Tree

Last Updated : 28 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Tree, the task is to replace the value of each node with the sum of all the nodes present in the same level.

Examples:

Input: 
 

             9
            / \
           6   10
          / \   \
         4   7   11
        / \   \
       3  5   8

Output: 
 

             9
            / \
          16   16
          / \   \
        22   22  22
        / \   \
      16  16   16

Explanation: 
The sum of nodes at level1: 9 
The sum of nodes at level2: 6 + 10 = 16 
The sum of nodes at level3: 4 + 7 + 11 = 22 
The sum of nodes at level4: 3 + 5 + 8 = 16 
 

 

Input: 
 

             5
            / \
           6   3
          / \   \
         4   9   2

Output: 
 

             5
            / \
           9   9
          / \   \
        15   15   15

 

 

Approach:The idea to find the sum of nodes at each level of the Tree and replace each node with the sum of nodes at that level using Level Order Traversal. Follow the steps below to solve the problem:

  • Initialize two queues, say que1 and que2, where the sum of nodes at each level can be calculated using que1 and replace each node with the sum of all the nodes at the same level using que2.
  • Use Level Order Traversal and calculate the sum of all the nodes at each level of the tree.
  • Use Level Order Traversal and replace each node with the sum of all the nodes at that level of the tree.
  • Finally, print the tree using Level Order Traversal .

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of the binary tree
struct TreeNode
{
  int val = 0;
  TreeNode *left,*right;
  TreeNode(int x)
  {
    val = x;
    left = NULL;
    right = NULL;
  }
};
 
// Function to replace each node of the tree
// with the sum of nodes in the same level
TreeNode* replaceLvl(TreeNode *root){
 
  // If root is null
  if (!root)
    return root;
 
  // Queue to store nodes
  // of each level of the Tree
  queue<TreeNode*> que1;
  queue<TreeNode*> que2;
  que1.push(root);
  que2.push(root);
 
  while (true)
  {
 
    // Stores length of que1
    int lenque1 = que1.size();
 
    // Stores length of que2
    int lenque2 = que2.size();
 
    // Stores sum of nodes at
    // each level of the tree
    int lvlsum = 0;
 
    if (lenque1 == 0)
      break;
 
    // Traverse the tree and store
    // the sum at each level
    while (lenque1 > 0)
    {
 
      // Stores the front element
      // of the queue
      auto temp = que1.front();
      que1.pop();
 
      // Update lvlsum
      lvlsum += temp->val;
 
      // If left subtree not null
      if (temp->left)
        que1.push(temp->left);
 
      // If right subtree not null
      if (temp->right)
        que1.push(temp->right);
 
      // Update lenque1
      lenque1 -= 1;
    }
 
    // Replace all the nodes of at
    // each level of the tree
    while (lenque2 > 0)
    {
 
      // Stores front element
      // of the queue
      auto temp = que2.front();
      que2.pop();
 
      // Replace current node with
      // the sum of nodes
      temp->val = lvlsum;
 
      // If left subtree is not null
      if (temp->left)
        que2.push(temp->left);
 
      // If right subtree is not null
      if (temp->right)
        que2.push(temp->right);
 
      // Update lenque2
      lenque2 -= 1;
    }
  }
  return root;
}
 
// Function to print level order
// traversal of the Binary Tree
void printLvl(TreeNode *root)
{
 
  // Push root node into queue
  queue<TreeNode*> que;
  que.push(root);
 
  while (true)
  {
 
    // Stores count of nodes
    // at each level
    int length = que.size();
 
    // If no nodes left
    if (length == 0)
      break;
 
    while (length)
    {
 
      //Stores front element
      // of the queue
      auto temp = que.front();
      que.pop();
      cout << temp->val << " ";
 
      // If left subtree is not null
      if (temp->left)
        que.push(temp->left);
 
      // If right subtree is not null
      if (temp->right)
        que.push(temp->right);
 
      // Update length
      length -= 1;
    }
    cout << endl;
  }
}
 
// Driver Code
int main()
{
 
  TreeNode *root = new TreeNode(4);
  root->left = new TreeNode(5);
  root->right = new TreeNode(7);
  root->left->left = new TreeNode(1);
  root->left->right = new TreeNode(3);
  root->right->right = new TreeNode(5);
 
  // To update the tree
  root = replaceLvl(root);
 
  // To display the updated tree
  printLvl(root);
 
  return 0;
}
 
// This code is contributed by mohit kumar 29


Java




// Java program for above approach
import java.util.*;
import java.lang.*;
 
class GFG
{
  // Structure of a Node
  static class TreeNode
  {
    int val;
    TreeNode left, right;
 
    TreeNode(int key)
    {
      val = key;
      left = null;
      right = null;
    }
  };
 
 
  // Function to replace each node of the tree
  // with the sum of nodes in the same level
  static TreeNode replaceLvl(TreeNode root){
 
    // If root is null
    if (root==null)
      return root;
 
    // Queue to store nodes
    // of each level of the Tree
    Queue<TreeNode> que1=new LinkedList<>();
    Queue<TreeNode> que2=new LinkedList<>();
    que1.add(root);
    que2.add(root);
 
    while (true)
    {
 
      // Stores length of que1
      int lenque1 = que1.size();
 
      // Stores length of que2
      int lenque2 = que2.size();
 
      // Stores sum of nodes at
      // each level of the tree
      int lvlsum = 0;
 
      if (lenque1 == 0)
        break;
 
      // Traverse the tree and store
      // the sum at each level
      while (lenque1 > 0)
      {
 
        // Stores the front element
        // of the queue
        TreeNode temp = que1.peek();
        que1.poll();
 
        // Update lvlsum
        lvlsum += temp.val;
 
        // If left subtree not null
        if (temp.left!=null)
          que1.add(temp.left);
 
        // If right subtree not null
        if (temp.right!=null)
          que1.add(temp.right);
 
        // Update lenque1
        lenque1 -= 1;
      }
 
      // Replace all the nodes of at
      // each level of the tree
      while (lenque2 > 0)
      {
 
        // Stores front element
        // of the queue
        TreeNode temp = que2.peek();
        que2.poll();
 
        // Replace current node with
        // the sum of nodes
        temp.val = lvlsum;
 
        // If left subtree is not null
        if (temp.left!=null)
          que2.add(temp.left);
 
        // If right subtree is not null
        if (temp.right!=null)
          que2.add(temp.right);
 
        // Update lenque2
        lenque2 -= 1;
      }
    }
    return root;
  }
 
  // Function to print level order
  // traversal of the Binary Tree
  static void printLvl(TreeNode root)
  {
 
    // Push root node into queue
    Queue<TreeNode> que = new LinkedList<>();
    que.add(root);
 
    while (true)
    {
 
      // Stores count of nodes
      // at each level
      int length = que.size();
 
      // If no nodes left
      if (length == 0)
        break;
 
      while (length>0)
      {
 
        //Stores front element
        // of the queue
        TreeNode temp = que.peek();
        que.poll();
        System.out.print(temp.val+" ");
 
        // If left subtree is not null
        if (temp.left != null)
          que.add(temp.left);
 
        // If right subtree is not null
        if (temp.right != null)
          que.add(temp.right);
 
        // Update length
        length -= 1;
      }
      System.out.println();
    }
  }
   
  // Driver function
  public static void main (String[] args) {
    TreeNode root = new TreeNode(4);
    root.left = new TreeNode(5);
    root.left.left = new TreeNode(1);
    root.left.right = new TreeNode(3);
    root.right = new TreeNode(7);
    root.right.right = new TreeNode(5);
 
    // To update the tree
    root = replaceLvl(root);
 
    // To display the updated tree
    printLvl(root);
 
  }
}
 
// This code is contributed by offbeat


Python3




# Python program to implement
# the above approach
 
# Structure of the binary tree
class TreeNode:
    def __init__(self, val = 0,
                left = None, right = None):
        self.val = val
        self.left = left
        self.right = right
 
# Function to replace each node of the tree
# with the sum of nodes in the same level
def replaceLvl(root):
 
    # If root is null
    if not root:
        return
 
    # Queue to store nodes
    # of each level of the Tree   
    que1 = [root]
    que2 = [root]
 
    while True:
 
        # Stores length of que1
        lenque1 = len(que1)
 
        # Stores length of que2
        lenque2 = len(que2)
 
        # Stores sum of nodes at
        # each level of the tree
        lvlsum = 0
        if not lenque1:
            break
 
        # Traverse the tree and store
        # the sum at each level
        while lenque1:
 
            # Stores the front element
            # of the queue
            temp = que1.pop(0)
 
            # Update lvlsum
            lvlsum += temp.val
 
            # If left subtree not null
            if temp.left:
                que1.append(temp.left)
 
            # If right subtree not null   
            if temp.right:
                que1.append(temp.right)
 
            # Update lenque1   
            lenque1 -= 1
 
        # Replace all the nodes of at
        # each level of the tree
        while lenque2:
 
            # Stores front element
            # of the queue
            temp = que2.pop(0)
 
            # Replace current node with
            # the sum of nodes
            temp.val = lvlsum
 
            # If left subtree is not null
            if temp.left:
                que2.append(temp.left)
 
            # If right subtree is not null   
            if temp.right:
                que2.append(temp.right)
 
            # Update lenque2   
            lenque2 -= 1
    return root
 
# Function to print level order
# traversal of the Binary Tree
def printLvl(root):
 
    # Push root node into queue
    que = [root]
    while True:
 
        # Stores count of nodes
        # at each level
        length = len(que)
 
        # If no nodes left
        if not length:
            break
 
        while length:
 
            # Stores front element
            # of the queue
            temp = que.pop(0)
            print(temp.val, end =' ')
 
            # If left subtree is not null
            if temp.left:
                que.append(temp.left)
 
            # If right subtree is not null   
            if temp.right:
                que.append(temp.right)
 
            # Update length   
            length -= 1
        print()
 
# Driver Code
 
root = TreeNode(4)
root.left = TreeNode(5)
root.right = TreeNode(7)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.right = TreeNode(5)
 
# To update the tree
root = replaceLvl(root)
 
# To display the updated tree
printLvl(root)


C#




// C# program for above approach
 
using System;
using System.Collections.Generic;
 
public class TreeNode
  {
    public int val;
    public TreeNode left, right;
  
    public TreeNode(int key)
    {
      val = key;
      left = null;
      right = null;
    }
  }
 
public class GFG{
     
    // Function to replace each node of the tree
  // with the sum of nodes in the same level
  static TreeNode replaceLvl(TreeNode root){
  
    // If root is null
    if (root==null)
      return root;
  
    // Queue to store nodes
    // of each level of the Tree
    Queue<TreeNode> que1=new Queue<TreeNode>();
    Queue<TreeNode> que2=new Queue<TreeNode>();
    que1.Enqueue(root);
    que2.Enqueue(root);
  
    while (true)
    {
  
      // Stores length of que1
      int lenque1 = que1.Count;
  
      // Stores length of que2
      int lenque2 = que2.Count;
  
      // Stores sum of nodes at
      // each level of the tree
      int lvlsum = 0;
  
      if (lenque1 == 0)
        break;
  
      // Traverse the tree and store
      // the sum at each level
      while (lenque1 > 0)
      {
  
        // Stores the front element
        // of the queue
        TreeNode temp = que1.Dequeue();
  
        // Update lvlsum
        lvlsum += temp.val;
  
        // If left subtree not null
        if (temp.left!=null)
          que1.Enqueue(temp.left);
  
        // If right subtree not null
        if (temp.right!=null)
          que1.Enqueue(temp.right);
  
        // Update lenque1
        lenque1 -= 1;
      }
  
      // Replace all the nodes of at
      // each level of the tree
      while (lenque2 > 0)
      {
  
        // Stores front element
        // of the queue
        TreeNode temp = que2.Dequeue();
  
        // Replace current node with
        // the sum of nodes
        temp.val = lvlsum;
  
        // If left subtree is not null
        if (temp.left!=null)
          que2.Enqueue(temp.left);
  
        // If right subtree is not null
        if (temp.right!=null)
          que2.Enqueue(temp.right);
  
        // Update lenque2
        lenque2 -= 1;
      }
    }
    return root;
  }
  
  // Function to print level order
  // traversal of the Binary Tree
  static void printLvl(TreeNode root)
  {
  
    // Push root node into queue
    Queue<TreeNode> que = new Queue<TreeNode>();
    que.Enqueue(root);
  
    while (true)
    {
  
      // Stores count of nodes
      // at each level
      int length = que.Count;
  
      // If no nodes left
      if (length == 0)
        break;
  
      while (length>0)
      {
  
        //Stores front element
        // of the queue
        TreeNode temp = que.Dequeue();
         
        Console.Write(temp.val+" ");
  
        // If left subtree is not null
        if (temp.left != null)
          que.Enqueue(temp.left);
  
        // If right subtree is not null
        if (temp.right != null)
          que.Enqueue(temp.right);
  
        // Update length
        length -= 1;
      }
      Console.WriteLine();
    }
  }
    
  // Driver function
     
    static public void Main (){
         
        TreeNode root = new TreeNode(4);
    root.left = new TreeNode(5);
    root.left.left = new TreeNode(1);
    root.left.right = new TreeNode(3);
    root.right = new TreeNode(7);
    root.right.right = new TreeNode(5);
  
    // To update the tree
    root = replaceLvl(root);
  
    // To display the updated tree
    printLvl(root);
         
    }
}
 
// This code is contributed by patel2127


Javascript




<script>
 
  // JavaScript program for above approach
  
  // Structure of a Node
  class TreeNode
  {
      constructor(key) {
         this.left = null;
         this.right = null;
         this.val = key;
      }
  }
   
  // Function to replace each node of the tree
  // with the sum of nodes in the same level
  function replaceLvl(root){
  
    // If root is null
    if (root==null)
      return root;
  
    // Queue to store nodes
    // of each level of the Tree
    let que1 = [];
    let que2 = [];
    que1.push(root);
    que2.push(root);
  
    while (true)
    {
  
      // Stores length of que1
      let lenque1 = que1.length;
  
      // Stores length of que2
      let lenque2 = que2.length;
  
      // Stores sum of nodes at
      // each level of the tree
      let lvlsum = 0;
  
      if (lenque1 == 0)
        break;
  
      // Traverse the tree and store
      // the sum at each level
      while (lenque1 > 0)
      {
  
        // Stores the front element
        // of the queue
        let temp = que1[0];
        que1.shift();
  
        // Update lvlsum
        lvlsum += temp.val;
  
        // If left subtree not null
        if (temp.left!=null)
          que1.push(temp.left);
  
        // If right subtree not null
        if (temp.right!=null)
          que1.push(temp.right);
  
        // Update lenque1
        lenque1 -= 1;
      }
  
      // Replace all the nodes of at
      // each level of the tree
      while (lenque2 > 0)
      {
  
        // Stores front element
        // of the queue
        let temp = que2[0];
        que2.shift();
  
        // Replace current node with
        // the sum of nodes
        temp.val = lvlsum;
  
        // If left subtree is not null
        if (temp.left!=null)
          que2.push(temp.left);
  
        // If right subtree is not null
        if (temp.right!=null)
          que2.push(temp.right);
  
        // Update lenque2
        lenque2 -= 1;
      }
    }
    return root;
  }
  
  // Function to print level order
  // traversal of the Binary Tree
  function printLvl(root)
  {
  
    // Push root node into queue
    let que = [];
    que.push(root);
  
    while (true)
    {
  
      // Stores count of nodes
      // at each level
      let length = que.length;
  
      // If no nodes left
      if (length == 0)
        break;
  
      while (length>0)
      {
  
        //Stores front element
        // of the queue
        let temp = que[0];
        que.shift();
        document.write(temp.val+" ");
  
        // If left subtree is not null
        if (temp.left != null)
          que.push(temp.left);
  
        // If right subtree is not null
        if (temp.right != null)
          que.push(temp.right);
  
        // Update length
        length -= 1;
      }
      document.write("</br>");
    }
  }
   
  let root = new TreeNode(4);
  root.left = new TreeNode(5);
  root.left.left = new TreeNode(1);
  root.left.right = new TreeNode(3);
  root.right = new TreeNode(7);
  root.right.right = new TreeNode(5);
 
  // To update the tree
  root = replaceLvl(root);
 
  // To display the updated tree
  printLvl(root);
     
</script>


Output: 

4 
12 12 
9 9 9

 

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



Similar Reads

Calculate sum of all nodes present in a level for each level of a Tree
Given a Generic Tree consisting of N nodes (rooted at 0) where each node is associated with a value, the task for each level of the Tree is to find the sum of all node values present at that level of the tree. Examples: Input: node_number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 } Output: Sum of level 0 = 2S
14 min read
Replace each node of a Binary Tree with the sum of all the nodes present in its diagonal
Given a Binary Tree, the task is to print the level order traversal of the tree after replacing the value of each node of the tree with the sum of all the nodes on the same diagonal. Examples: Input: 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 Output: 30 21 30 9 21 30 3 9 21 Explanation: 30 / \ 21 30 / \ \ 9 21 30 / \ \ 3 9 21 Diagonal traversal of the bin
11 min read
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
Given a Binary Tree, the task is for each level is to print the total number of nodes from all lower levels which are less than or equal to every node present at that level. Examples: Input: Below is the given tree: 4 / \ 3 5 / \ / \ 10 2 3 1 Output: 4 3 0Explanation:Nodes in level 1 has 4 nodes as (3) in level 2 and (2, 3, 1) in level 3. Nodes in
11 min read
Print the nodes corresponding to the level value for each level of a Binary Tree
Given a Binary Tree, the task for each level L is to print the Lth node of the tree. If the Lth node is not present for any level, print -1. Note: Consider the root node to be at the level 1 of the binary tree. Examples: Input: Below is the given Tree: Output:Level 1: 1Level 2: 3 Level 3: 6Level 4: 11Explanation:For the first level, the 1st node is
15 min read
Sum of Bitwise AND of the sum of all leaf and non-leaf nodes for each level of a Binary Tree
Given a Binary Tree consisting of N nodes, the task is to find the sum of Bitwise AND of the sum of all leaf nodes and the sum of all non-leaf nodes for each level in the given Tree. Examples: Input: Below is the given tree: 5 / \ 3 9 / \ 6 4 \ 7Output: 5Explanation: For Level 1: leaf node sum = 0, non-leaf node sum = 5. So, 0&amp;5 = 0. For Level
10 min read
Minimum value to be added at each level in Binary Tree to make all level sum equal
Given a binary tree, the task is to find all minimum values greater than or equal to zero, that should be added at each level to make the sum at each level equal. Examples: Input: 1 / \ 2 3 / \ 4 5 Output: 8 4 0Explanation: Initial sum at each level is {1, 5, 9}. To make all levels sum equal minimum values to be added are {8, 4, 0}. So the final su
9 min read
Sum of decimal equivalents of binary node values in each level of a Binary Tree
Given a Binary Tree consisting of nodes with values 0 and 1 only, the task is to find the total sum of the decimal equivalents of the binary numbers formed by connecting nodes at the same level from left to right, on each level. Examples: Input: Below is the given Tree: 0 / \ 1 0 / \ / \ 0 1 1 1Output: 9Explanation: Binary number formed at level 1
15 min read
Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, ...) nodes are printed f
18 min read
Modify a Binary Tree by adding a level of nodes with given value at a specified level
Given a Binary Tree consisting of N nodes and two integers K and L, the task is to add one row of nodes of value K at the Lth level, such that the orientation of the original tree remains unchanged. Examples: Input: K = 1, L = 2 Output:11 12 34 5 6 Explanation:Below is the tree after inserting node with value 1 in the K(= 2) th level. Input: K = 1,
32 min read
Difference between sums of odd level and even level nodes of a Binary Tree
Given a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on. For example, in the following tree, sum of nodes at odd level is (5 + 1 + 4 + 8) which is 18. And sum of nodes at even level is (2 + 6 + 3 + 7 + 9) which i
20 min read
Article Tags :
Practice Tags :