Open In App

Sum of decimal equivalents of binary node values in each level of a Binary Tree

Improve
Improve
Like Article
Like
Save
Share
Report

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  1
Output: 9
Explanation: 
Binary number formed at level 1 is “0” and its decimal equivalent is 0.
Binary number formed at level 2 is “10” and its decimal equivalent is 2.
Binary number formed at level 3 is “0111” and its decimal equivalent is 7.
Therefore, total sum = 0 + 2 + 7 = 9.

Input: Below is the given Tree:
                 0
               /
             1
            / \
          1   0
Output: 3

Approach: The idea is to perform level order traversal using a queue and find the sum of numbers formed at each level. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++




// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a Tree Node
class TreeNode {
 public:
  int val;
  TreeNode *left, *right;
 
  TreeNode(int key) {
    val = key;
    left = right = NULL;
  }
};
 
// Function to convert binary number
// to its equivalent decimal value
int convertBinaryToDecimal(vector<int> arr) {
  int ans = 0;
  for (int i : arr) ans = (ans << 1) | i;
 
  return ans;
}
 
// Function to calculate sum of
// decimal equivalent of binary numbers
// of node values present at each level
void decimalEquilvalentAtEachLevel(TreeNode *root) {
  int ans = 0;
 
  queue<TreeNode *> que;
 
  // Push root node into queue
  que.push(root);
 
  while (true) {
    int length = que.size();
    if (length == 0) break;
    vector<int> eachLvl;
 
    // Connect nodes at the same
    // level to form a binary number
    while (length > 0) {
      TreeNode *temp = que.front();
      que.pop();
 
      // Append the value of the
      // current node to eachLvl
      eachLvl.push_back(temp->val);
 
      // Insert the Left child to
      // queue, if its not NULL
      if (temp->left != NULL) que.push(temp->left);
 
      // Insert the Right child to
      // queue, if its not NULL
      if (temp->right != NULL) que.push(temp->right);
 
      // Decrement length by one
      length -= 1;
 
      // Stores the front
      // element of the queue
    }
 
    // Add decimal equivalent of the
    // binary number formed on the
    // current level to ans
    ans += convertBinaryToDecimal(eachLvl);
  }
 
  // Finally print ans
  cout << ans << endl;
}
 
// Driver Code
int main()
{
   
  // Given Tree
  TreeNode *root = new TreeNode(0);
  root->left = new TreeNode(1);
  root->right = new TreeNode(0);
  root->left->left = new TreeNode(0);
  root->left->right = new TreeNode(1);
  root->right->left = new TreeNode(1);
  root->right->right = new TreeNode(1);
 
  // Function Call
  decimalEquilvalentAtEachLevel(root);
 
  return 0;
}
 
// This code is contributed by sanjeev2552


Java




// Java program for the above approach
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
 
class GFG {
 
    // Structure of a Tree Node
    static class TreeNode {
        int val;
        TreeNode left, right;
 
        public TreeNode(int key) {
            val = key;
            left = right = null;
        }
    }
 
    // Function to convert binary number
    // to its equivalent decimal value
    static int convertBinaryToDecimal(ArrayList<Integer> arr) {
        int ans = 0;
        for (int i : arr)
            ans = (ans << 1) | i;
 
        return ans;
 
    }
 
    // Function to calculate sum of
    // decimal equivalent of binary numbers
    // of node values present at each level
    static void decimalEquilvalentAtEachLevel(TreeNode root) {
 
        int ans = 0;
 
        Queue<TreeNode> que = new LinkedList<>();
 
        // Push root node into queue
        que.add(root);
 
        while (true) {
            int length = que.size();
            if (length == 0)
                break;
            ArrayList<Integer> eachLvl = new ArrayList<>();
 
            // Connect nodes at the same
            // level to form a binary number
            while (length > 0) {
 
                TreeNode temp = que.poll();
 
                // Append the value of the
                // current node to eachLvl
                eachLvl.add(temp.val);
 
                // Insert the Left child to
                // queue, if its not NULL
                if (temp.left != null)
                    que.add(temp.left);
 
                // Insert the Right child to
                // queue, if its not NULL
                if (temp.right != null)
                    que.add(temp.right);
 
                // Decrement length by one
                length -= 1;
 
                // Stores the front
                // element of the queue
            }
 
            // Add decimal equivalent of the
            // binary number formed on the
            // current level to ans
            ans += convertBinaryToDecimal(eachLvl);
        }
 
        // Finally print ans
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String[] args) {
 
        // Given Tree
        TreeNode root = new TreeNode(0);
        root.left = new TreeNode(1);
        root.right = new TreeNode(0);
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(1);
        root.right.left = new TreeNode(1);
        root.right.right = new TreeNode(1);
 
        // Function Call
        decimalEquilvalentAtEachLevel(root);
    }
 
    // This code is contributed by sanjeev2552
}


Python3




# Python3 program for the above approach
 
# Structure of a Tree Node
class TreeNode:
    def __init__(self, val = 0,
                 left = None, right = None):
        self.val = val
        self.left = left
        self.right = right
 
# Function to convert binary number
# to its equivalent decimal value
def convertBinaryToDecimal(arr):
 
    ans = 0
 
    for i in arr:
        ans = (ans << 1) | i
 
    return ans
 
# Function to calculate sum of
# decimal equivalent of binary numbers
# of node values present at each level
def decimalEquilvalentAtEachLevel(root):
 
    ans = 0
     
    # Push root node into queue
    que = [root]
 
    while True:
        length = len(que)
        if not length:
            break
        eachLvl = []
         
        # Connect nodes at the same
        # level to form a binary number
        while length:
           
            # Stores the front
            # element of the queue
            temp = que.pop(0)
 
            # Append the value of the
            # current node to eachLvl
            eachLvl.append(temp.val)
 
            # Insert the Left child to
            # queue, if its not NULL
            if temp.left:
                que.append(temp.left)
 
            # Insert the Right child to
            # queue, if its not NULL
            if temp.right:
                que.append(temp.right)
                 
            # Decrement length by one
            length -= 1
             
        # Add decimal equivalent of the
        # binary number formed on the
        # current level to ans
        ans += convertBinaryToDecimal(eachLvl)
 
    # Finally print ans
    print(ans)
 
 
# Driver Code
 
# Given Tree
root = TreeNode(0)
root.left = TreeNode(1)
root.right = TreeNode(0)
root.left.left = TreeNode(0)
root.left.right = TreeNode(1)
root.right.left = TreeNode(1)
root.right.right = TreeNode(1)
 
# Function Call
decimalEquilvalentAtEachLevel(root)


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
    
   // Structure of a Tree Node
class TreeNode{
  public int val;
  public TreeNode left,right;
};
 
static TreeNode newNode(int key){
  TreeNode temp = new TreeNode();
  temp.val = key;
  temp.left = temp.right = null;
  return temp;
}
// Function to convert binary number
// to its equivalent decimal value
static int convertBinaryToDecimal(List<int> arr)
{  
   int ans = 0;
    foreach(int i in arr)
        ans = (ans << 1) | i;
 
    return ans;
 
}
 
// Function to calculate sum of
// decimal equivalent of binary numbers
// of node values present at each level
static void decimalEquilvalentAtEachLevel(TreeNode root){
 
    int ans = 0;
     
    Queue<TreeNode> que = new Queue<TreeNode>();
   
    // Push root node into queue
    que.Enqueue(root);
 
    while(true){
       int length = que.Count;
        if (length == 0)
            break;
        List<int> eachLvl = new List<int>();
         
        // Connect nodes at the same
        // level to form a binary number
        while(length > 0){
 
          TreeNode temp = que.Peek();
          que.Dequeue();
 
            // Append the value of the
            // current node to eachLvl
            eachLvl.Add(temp.val);
 
            // Insert the Left child to
            // queue, if its not NULL
            if (temp.left != null)
                que.Enqueue(temp.left);
 
            // Insert the Right child to
            // queue, if its not NULL
            if (temp.right!=null)
                que.Enqueue(temp.right);
                 
            // Decrement length by one
            length -= 1;
           
            // Stores the front
            // element of the queue
        }
             
        // Add decimal equivalent of the
        // binary number formed on the
        // current level to ans
        ans += convertBinaryToDecimal(eachLvl);
    }
 
    // Finally print ans
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main()
{
   
    // Given Tree
TreeNode root = newNode(0);
root.left = newNode(1);
root.right = newNode(0);
root.left.left = newNode(0);
root.left.right = newNode(1);
root.right.left = newNode(1);
root.right.right = newNode(1);
 
// Function Call
decimalEquilvalentAtEachLevel(root);
}
}
 
// This code is contributed by SURENDRA_GANGWAR.


Javascript




<script>
 
// JavaScript program for the above approach
 
   // Structure of a Tree Node
class TreeNode{
 
  constructor()
  {
    this.val = 0;
    this.left = null;
    this.right = null;
  }
};
 
function newNode( key){
  var temp = new TreeNode();
  temp.val = key;
  temp.left = temp.right = null;
  return temp;
}
// Function to convert binary number
// to its equivalent decimal value
function convertBinaryToDecimal(arr)
{  
   var ans = 0;
    for(var i of arr)
        ans = (ans << 1) | i;
 
    return ans;
 
}
 
// Function to calculate sum of
// decimal equivalent of binary numbers
// of node values present at each level
function decimalEquilvalentAtEachLevel( root){
 
    var ans = 0;
     
    var que = [];
   
    // Push root node into queue
    que.push(root);
 
    while(true){
       var length = que.length;
        if (length == 0)
            break;
        var eachLvl = [];
         
        // Connect nodes at the same
        // level to form a binary number
        while(length > 0){
 
          var temp = que[0];
          que.shift();
 
            // Append the value of the
            // current node to eachLvl
            eachLvl.push(temp.val);
 
            // Insert the Left child to
            // queue, if its not NULL
            if (temp.left != null)
                que.push(temp.left);
 
            // Insert the Right child to
            // queue, if its not NULL
            if (temp.right!=null)
                que.push(temp.right);
                 
            // Decrement length by one
            length -= 1;
           
            // Stores the front
            // element of the queue
        }
             
        // Add decimal equivalent of the
        // binary number formed on the
        // current level to ans
        ans += convertBinaryToDecimal(eachLvl);
    }
 
    // Finally print ans
    document.write(ans);
}
 
// Driver Code
 
// Given Tree
var root = newNode(0);
root.left = newNode(1);
root.right = newNode(0);
root.left.left = newNode(0);
root.left.right = newNode(1);
root.right.left = newNode(1);
root.right.right = newNode(1);
 
// Function Call
decimalEquilvalentAtEachLevel(root);
 
</script>


Output

9







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

New Approach:- Here is another approach to solving this problem

Below is the implementation of the above approach:

C++




#include <iostream>
#include <queue>
using namespace std;
 
class TreeNode {
public:
    int val;
    TreeNode* left;
    TreeNode* right;
 
    TreeNode(int val) {
        this->val = val;
        this->left = nullptr;
        this->right = nullptr;
    }
};
 
// Function to calculate the decimal equivalent at each
// level of a binary tree
int decimalEquivalentAtEachLevel(TreeNode* root) {
    if (!root) {
        return 0;
    }
 
    queue<TreeNode*> q;
    q.push(root);
    int level_sum = 0;
 
    while (!q.empty()) {
        int level_size = q.size();
        int level_sum_temp = 0;
 
        // Process each node at the current level
        while (level_size > 0) {
            TreeNode* node = q.front();
            q.pop();
            level_sum_temp = level_sum_temp * 2 + node->val;
 
            // Add the left child to the queue if it exists
            if (node->left) {
                q.push(node->left);
            }
 
            // Add the right child to the queue if it exists
            if (node->right) {
                q.push(node->right);
            }
 
            level_size--;
        }
 
        // Add the sum of binary values at the current level to the total sum
        level_sum += level_sum_temp;
    }
 
    // Return the decimal equivalent sum at each level
    return level_sum;
}
 
int main() {
    // Create the Binary Tree
    TreeNode* root = new TreeNode(0);
    root->left = new TreeNode(1);
    root->right = new TreeNode(0);
    root->left->left = new TreeNode(0);
    root->left->right = new TreeNode(1);
    root->right->left = new TreeNode(1);
    root->right->right = new TreeNode(1);
 
    // Calculate the sum
    int result = decimalEquivalentAtEachLevel(root);
    cout << result << endl;
 
    // Free memory (optional, but recommended)
    delete root->left->right;
    delete root->left->left;
    delete root->right->right;
    delete root->right->left;
    delete root->left;
    delete root->right;
    delete root;
 
    return 0;
}


Java




// Java code implementation
 
import java.util.LinkedList;
import java.util.Queue;
 
// creating tree node
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
 
    TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
 
public class BinaryTree {
    // Function to calculate the decimal equivalent at each
    // level of a binary tree
    public static int decimalEquivalentAtEachLevel(TreeNode root) {
        if (root == null) {
            return 0;
        }
 
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int levelSum = 0;
 
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            int levelSumTemp = 0;
 
            // Process each node at the current level
            while (levelSize > 0) {
                TreeNode node = queue.poll();
                levelSumTemp = levelSumTemp * 2 + node.val;
 
                // Add the left child to the queue if it exists
                if (node.left != null) {
                    queue.add(node.left);
                }
 
                // Add the right child to the queue if it exists
                if (node.right != null) {
                    queue.add(node.right);
                }
 
                levelSize--;
            }
 
            // Add the sum of binary values at the current level to the total sum
            levelSum += levelSumTemp;
        }
 
        // Return the decimal equivalent sum at each level
        return levelSum;
    }
   
    // Function to delete the binary tree and free memory
    private static void deleteTree(TreeNode root) {
        if (root == null) {
            return;
        }
 
        deleteTree(root.left);
        deleteTree(root.right);
        root.left = null;
        root.right = null;
    }
   
    public static void main(String[] args) {
        // Create the Binary Tree
        TreeNode root = new TreeNode(0);
        root.left = new TreeNode(1);
        root.right = new TreeNode(0);
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(1);
        root.right.left = new TreeNode(1);
        root.right.right = new TreeNode(1);
 
        // Calculate the sum
        int result = decimalEquivalentAtEachLevel(root);
        System.out.println(result);
 
        // Free memory (optional, but recommended)
        deleteTree(root);
    }
 
}


Python




from collections import deque
 
 
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
 
 
def decimalEquivalentAtEachLevel(root):
    if not root:
        return 0
 
    queue = deque()
    queue.append(root)
    level_sum = 0
 
    while queue:
        level_size = len(queue)
        level_sum_temp = 0
 
        while level_size > 0:
            node = queue.popleft()
            level_sum_temp = level_sum_temp * 2 + node.val
 
            if node.left:
                queue.append(node.left)
 
            if node.right:
                queue.append(node.right)
 
            level_size -= 1
 
        level_sum += level_sum_temp
 
    return level_sum
 
 
# Create the Binary Tree
root = TreeNode(0)
root.left = TreeNode(1)
root.right = TreeNode(0)
root.left.left = TreeNode(0)
root.left.right = TreeNode(1)
root.right.left = TreeNode(1)
root.right.right = TreeNode(1)
 
# Calculate the sum
result = decimalEquivalentAtEachLevel(root)
print(result)


C#




using System;
using System.Collections.Generic;
 
public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
 
    public TreeNode(int val)
    {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
 
public class BinaryTree
{
    // Function to calculate the decimal equivalent at each
    // level of a binary tree
    public static int DecimalEquivalentAtEachLevel(TreeNode root)
    {
        if (root == null)
        {
            return 0;
        }
 
        Queue<TreeNode> queue = new Queue<TreeNode>();
        queue.Enqueue(root);
        int level_sum = 0;
 
        while (queue.Count > 0)
        {
            int level_size = queue.Count;
            int level_sum_temp = 0;
 
            // Process each node at the current level
            while (level_size > 0)
            {
                TreeNode node = queue.Dequeue();
                level_sum_temp = level_sum_temp * 2 + node.val;
 
                // Add the left child to the queue if it exists
                if (node.left != null)
                {
                    queue.Enqueue(node.left);
                }
 
                // Add the right child to the queue if it exists
                if (node.right != null)
                {
                    queue.Enqueue(node.right);
                }
 
                level_size--;
            }
 
            // Add the sum of binary values at the current level to the total sum
            level_sum += level_sum_temp;
        }
 
        // Return the decimal equivalent sum at each level
        return level_sum;
    }
 
    public static void Main()
    {
        // Create the Binary Tree
        TreeNode root = new TreeNode(0);
        root.left = new TreeNode(1);
        root.right = new TreeNode(0);
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(1);
        root.right.left = new TreeNode(1);
        root.right.right = new TreeNode(1);
 
        // Calculate the sum
        int result = DecimalEquivalentAtEachLevel(root);
        Console.WriteLine(result);
 
        // Free memory (optional, but recommended)
        DeleteTree(root);
 
        Console.ReadLine();
    }
 
    // Function to delete the binary tree and free memory
    private static void DeleteTree(TreeNode root)
    {
        if (root == null)
        {
            return;
        }
 
        DeleteTree(root.left);
        DeleteTree(root.right);
        root.left = null;
        root.right = null;
    }
}


Javascript




// Define a class for binary tree nodes
class TreeNode {
    constructor(val) {
        this.val = val; // The value of the node
        this.left = null; // Pointer to the left child node
        this.right = null; // Pointer to the right child node
    }
}
 
// Function to calculate the decimal equivalent at each level of a binary tree
function decimalEquivalentAtEachLevel(root) {
    if (!root) {
        return 0; // If the tree is empty, return 0
    }
 
    const queue = []; // Create a queue for level-order traversal
    queue.push(root); // Initialize the queue with the root node
    let levelSum = 0; // Initialize the total sum
 
    while (queue.length > 0) {
        const levelSize = queue.length; // Get the number of nodes at the current level
        let levelSumTemp = 0; // Initialize the sum for the current level
 
        // Process each node at the current level
        for (let i = 0; i < levelSize; i++) {
            const node = queue.shift(); // Remove the first node from the queue
            levelSumTemp = levelSumTemp * 2 + node.val; // Calculate the binary value at this level
 
            // Add the left child to the queue if it exists
            if (node.left) {
                queue.push(node.left);
            }
 
            // Add the right child to the queue if it exists
            if (node.right) {
                queue.push(node.right);
            }
        }
 
        // Add the sum of binary values at the current level to the total sum
        levelSum += levelSumTemp;
    }
 
    // Return the decimal equivalent sum at each level
    return levelSum;
}
 
// Create the Binary Tree
const root = new TreeNode(0);
root.left = new TreeNode(1);
root.right = new TreeNode(0);
root.left.left = new TreeNode(0);
root.left.right = new TreeNode(1);
root.right.left = new TreeNode(1);
root.right.right = new TreeNode(1);
 
// Calculate the sum
const result = decimalEquivalentAtEachLevel(root);
console.log(result); // Output the result
 
// Note: JavaScript automatically manages memory, so manual memory deallocation is not required.


Output

9







Time complexity: O(N)
Auxiliary space: O(M)



Last Updated : 04 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads