Find multiplication of sums of data of leaves at same levels
Given a Binary Tree, return following value for it.
1) For every level, compute sum of all leaves if there are leaves at this level. Otherwise, ignore it.
2) Return multiplication of all sums.
Examples:
Input: Root of below tree
2
/ \
7 5
\
9
Output: 63
First levels doesn't have leaves. Second level
has one leaf 7 and third level also has one
leaf 9. Therefore result is 7*9 = 63
Input: Root of below tree
2
/ \
7 5
/ \ \
8 6 9
/ \ / \
1 11 4 10
Output: 208
First two levels don't have leaves. Third
level has single leaf 8. Last level has four
leaves 1, 11, 4 and 10. Therefore result is
8 * (1 + 11 + 4 + 10)
We strongly recommend you to minimize your browser and try this yourself first.
Recursive approach: Using a Depth-First Search (DFS) Traversal
In this approach, perform a recursive DFS traversal of the binary tree and keep track of the sum of the data of the leaves at each level in a map. Once we have computed the sums for all levels, Iterate through the map and compute the multiplication of the sums of data for each level.
C++14
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode( int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = nullptr;
return node;
}
void dfs(Node* root, int level,
unordered_map< int , int >& sums)
{
if (root == nullptr) {
return ;
}
if (root->left == nullptr && root->right == nullptr) {
sums[level] += root->data;
return ;
}
dfs(root->left, level + 1, sums);
dfs(root->right, level + 1, sums);
}
int main()
{
Node* root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->left = newNode(8);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
root->right->right->right = newNode(10);
unordered_map< int , int > sums;
dfs(root, 0, sums);
long long ans = 1;
for ( const auto & p : sums) {
ans *= p.second;
}
cout << "Final product value = " << ans << endl;
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
class Node {
int data;
Node left;
Node right;
Node( int data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
public class Main {
public static void dfs(Node root, int level, Map<Integer, Integer> sums) {
if (root == null ) {
return ;
}
if (root.left == null && root.right == null ) {
sums.put(level, sums.getOrDefault(level, 0 ) + root.data);
return ;
}
dfs(root.left, level + 1 , sums);
dfs(root.right, level + 1 , sums);
}
public static void main(String[] args) {
Node root = new Node( 2 );
root.left = new Node( 7 );
root.right = new Node( 5 );
root.left.right = new Node( 6 );
root.left.left = new Node( 8 );
root.left.right.left = new Node( 1 );
root.left.right.right = new Node( 11 );
root.right.right = new Node( 9 );
root.right.right.left = new Node( 4 );
root.right.right.right = new Node( 10 );
Map<Integer, Integer> sums = new HashMap<>();
dfs(root, 0 , sums);
int ans = 1 ;
for ( int value : sums.values()) {
ans *= value;
}
System.out.println( "Final product value = " + ans);
}
}
|
Python3
from typing import Dict
from collections import defaultdict
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def dfs(root: Node, level: int , sums: Dict [ int , int ]) - > None :
if not root:
return
if not root.left and not root.right:
sums[level] + = root.data
return
dfs(root.left, level + 1 , sums)
dfs(root.right, level + 1 , sums)
if __name__ = = '__main__' :
root = Node( 2 )
root.left = Node( 7 )
root.right = Node( 5 )
root.left.right = Node( 6 )
root.left.left = Node( 8 )
root.left.right.left = Node( 1 )
root.left.right.right = Node( 11 )
root.right.right = Node( 9 )
root.right.right.left = Node( 4 )
root.right.right.right = Node( 10 )
sums = defaultdict( int )
dfs(root, 0 , sums)
ans = 1
for value in sums.values():
ans * = value
print ( "Final product value =" , ans)
|
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
this .left = this .right = null ;
}
}
class Program {
static void dfs(Node root, int level,
Dictionary< int , int > sums)
{
if (root == null ) {
return ;
}
if (root.left == null && root.right == null ) {
if (sums.ContainsKey(level)) {
sums[level] += root.data;
}
else {
sums[level] = root.data;
}
return ;
}
dfs(root.left, level + 1, sums);
dfs(root.right, level + 1, sums);
}
static void Main( string [] args)
{
Node root = new Node(2);
root.left = new Node(7);
root.right = new Node(5);
root.left.right = new Node(6);
root.left.left = new Node(8);
root.left.right.left = new Node(1);
root.left.right.right = new Node(11);
root.right.right = new Node(9);
root.right.right.left = new Node(4);
root.right.right.right = new Node(10);
Dictionary< int , int > sums
= new Dictionary< int , int >();
dfs(root, 0, sums);
long ans = 1;
foreach (KeyValuePair< int , int > p in sums)
{
ans *= p.Value;
}
Console.WriteLine( "Final product value = " + ans);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function newNode(data) {
const node = new Node(data);
return node;
}
function dfs(root, level, sums) {
if (root === null ) {
return ;
}
if (root.left === null && root.right === null ) {
if (sums.has(level)) {
sums.set(level, sums.get(level) + root.data);
} else {
sums.set(level, root.data);
}
return ;
}
dfs(root.left, level + 1, sums);
dfs(root.right, level + 1, sums);
}
const root = newNode(2);
root.left = newNode(7);
root.right = newNode(5);
root.left.right = newNode(6);
root.left.left = newNode(8);
root.left.right.left = newNode(1);
root.left.right.right = newNode(11);
root.right.right = newNode(9);
root.right.right.left = newNode(4);
root.right.right.right = newNode(10);
const sums = new Map();
dfs(root, 0, sums);
let ans = 1;
for (const value of sums.values()) {
ans *= value;
}
console.log(`Final product value = ${ans}`);
|
Output
Final product value = 208
Time Complexity: O(n), where n is the number of nodes in the binary tree
Auxiliary Space: O(h), where h is the height of the binary tree (space used by the call stack during recursion)
An Efficient Solution is to use Queue based level order traversal. While doing the traversal, process all different levels separately. For every processed level, check if it has leaves. If it has then compute sum of leaf nodes. Finally return product of all sums.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
bool isLeaf(Node* root)
{
return (!root->left && !root->right);
}
int sumAndMultiplyLevelData(Node* root)
{
if (!root)
return 0;
int mul = 1;
queue<Node*> q;
q.push(root);
while (1) {
int NodeCount = q.size();
if (NodeCount == 0)
break ;
int levelSum = 0;
bool leafFound = false ;
while (NodeCount > 0) {
Node* Node = q.front();
if (isLeaf(Node)) {
leafFound = true ;
levelSum += Node->data;
}
q.pop();
if (Node->left != NULL)
q.push(Node->left);
if (Node->right != NULL)
q.push(Node->right);
NodeCount--;
}
if (leafFound)
mul *= levelSum;
}
return mul;
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
int main()
{
Node* root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->left = newNode(8);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
root->right->right->right = newNode(10);
cout << "Final product value = "
<< sumAndMultiplyLevelData(root) << endl;
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
class Node {
int data;
Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree {
Node root;
boolean isLeaf(Node node)
{
return ((node.left == null ) && (node.right == null ));
}
int sumAndMultiplyLevelData()
{
return sumAndMultiplyLevelData(root);
}
int sumAndMultiplyLevelData(Node node)
{
if (node == null ) {
return 0 ;
}
int mul = 1 ;
LinkedList<Node> q = new LinkedList<Node>();
q.add(node);
while ( true ) {
int NodeCount = q.size();
if (NodeCount == 0 ) {
break ;
}
int levelSum = 0 ;
boolean leafFound = false ;
while (NodeCount > 0 ) {
Node node1;
node1 = q.poll();
if (isLeaf(node1)) {
leafFound = true ;
levelSum += node1.data;
}
if (node1.left != null ) {
q.add(node1.left);
}
if (node1.right != null ) {
q.add(node1.right);
}
NodeCount--;
}
if (leafFound) {
mul *= levelSum;
}
}
return mul;
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 2 );
tree.root.left = new Node( 7 );
tree.root.right = new Node( 5 );
tree.root.left.left = new Node( 8 );
tree.root.left.right = new Node( 6 );
tree.root.left.right.left = new Node( 1 );
tree.root.left.right.right = new Node( 11 );
tree.root.right.right = new Node( 9 );
tree.root.right.right.left = new Node( 4 );
tree.root.right.right.right = new Node( 10 );
System.out.println( "The final product value : "
+ tree.sumAndMultiplyLevelData());
}
}
|
Python3
class newNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def isLeaf(root) :
return ( not root.left and
not root.right)
def sumAndMultiplyLevelData( root) :
if ( not root) :
return 0
mul = 1
q = []
q.append(root)
while ( 1 ):
NodeCount = len (q)
if (NodeCount = = 0 ) :
break
levelSum = 0
leafFound = False
while (NodeCount > 0 ) :
Node = q[ 0 ]
if (isLeaf(Node)) :
leafFound = True
levelSum + = Node.data
q.pop( 0 )
if (Node.left ! = None ) :
q.append(Node.left)
if (Node.right ! = None ) :
q.append(Node.right)
NodeCount - = 1
if (leafFound) :
mul * = levelSum
return mul
if __name__ = = '__main__' :
root = newNode( 2 )
root.left = newNode( 7 )
root.right = newNode( 5 )
root.left.right = newNode( 6 )
root.left.left = newNode( 8 )
root.left.right.left = newNode( 1 )
root.left.right.right = newNode( 11 )
root.right.right = newNode( 9 )
root.right.right.left = newNode( 4 )
root.right.right.right = newNode( 10 )
print ( "Final product value = " ,
sumAndMultiplyLevelData(root))
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class BinaryTree
{
Node root;
bool isLeaf(Node node)
{
return ((node.left == null ) &&
(node.right == null ));
}
int sumAndMultiplyLevelData()
{
return sumAndMultiplyLevelData(root);
}
int sumAndMultiplyLevelData(Node node)
{
if (node == null ) {
return 0;
}
int mul = 1;
Queue<Node> q = new Queue<Node>();
q.Enqueue(node);
while ( true ) {
int NodeCount = q.Count;
if (NodeCount == 0)
{
break ;
}
int levelSum = 0;
bool leafFound = false ;
while (NodeCount > 0)
{
Node node1;
node1 = q.Dequeue();
if (isLeaf(node1))
{
leafFound = true ;
levelSum += node1.data;
}
if (node1.left != null )
{
q.Enqueue(node1.left);
}
if (node1.right != null )
{
q.Enqueue(node1.right);
}
NodeCount--;
}
if (leafFound)
{
mul *= levelSum;
}
}
return mul;
}
public static void Main(String []args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(2);
tree.root.left = new Node(7);
tree.root.right = new Node(5);
tree.root.left.left = new Node(8);
tree.root.left.right = new Node(6);
tree.root.left.right.left = new Node(1);
tree.root.left.right.right = new Node(11);
tree.root.right.right = new Node(9);
tree.root.right.right.left = new Node(4);
tree.root.right.right.right = new Node(10);
Console.WriteLine( "The final product value : "
+ tree.sumAndMultiplyLevelData());
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .data=data;
this .left = this .right = null ;
}
}
let root;
function isLeaf(node)
{
return ((node.left == null ) && (node.right == null ));
}
function sumAndMultiplyLevelData(node)
{
if (node == null ) {
return 0;
}
let mul = 1;
let q = [];
q.push(node);
while ( true ) {
let NodeCount = q.length;
if (NodeCount == 0) {
break ;
}
let levelSum = 0;
let leafFound = false ;
while (NodeCount > 0) {
let node1= q.shift();
if (isLeaf(node1)) {
leafFound = true ;
levelSum += node1.data;
}
if (node1.left != null ) {
q.push(node1.left);
}
if (node1.right != null ) {
q.push(node1.right);
}
NodeCount--;
}
if (leafFound) {
mul *= levelSum;
}
}
return mul;
}
root = new Node(2);
root.left = new Node(7);
root.right = new Node(5);
root.left.left = new Node(8);
root.left.right = new Node(6);
root.left.right.left = new Node(1);
root.left.right.right = new Node(11);
root.right.right = new Node(9);
root.right.right.left = new Node(4);
root.right.right.right = new Node(10);
document.write( "The final product value : "
+ sumAndMultiplyLevelData(root));
</script>
|
Output:
Final product value = 208
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue data structure.
Last Updated :
21 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...