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:
- Initialize a queue, say Q, to perform the level order traversal and a variable, say ans, to store the sum of number formed.
- Push the root node to the queue Q.
- Iterate until the queue becomes empty and perform the following steps:
- Iterate over the range [1, Q.size()] and connect all the nodes at that level and push the children of the respective nodes in the queue Q.
- Find decimal equivalent of the binary number formed and add this number to ans.
- After completing the above steps, print the value of ans as the resultant sum.
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 Nodeclass TreeNode { public: int val; TreeNode *left, *right; TreeNode(int key) { val = key; left = right = NULL; }};// Function to convert binary number// to its equivalent decimal valueint 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 levelvoid 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 Codeint 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 approachimport 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 Nodeclass 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 valuedef 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 leveldef 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 Treeroot = 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 CalldecimalEquilvalentAtEachLevel(root) |
C#
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Structure of a Tree Nodeclass 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 valuestatic 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 levelstatic 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 Codepublic static void Main(){ // Given TreeTreeNode 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 CalldecimalEquilvalentAtEachLevel(root);}}// This code is contributed by SURENDRA_GANGWAR. |
9
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

