Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Find maximum level sum in Binary Tree
Next article icon

Find maximum level product in Binary Tree

Last Updated : 14 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree having positive and negative nodes, the task is to find maximum product level in it.

Examples: 

Input :               4                     /   \                    2    -5                   / \    /\                 -1   3 -2  6 Output: 36 Explanation : Product of all nodes of 0'th level is 4 Product of all nodes of 1'th level is -10 Product of all nodes of 2'th level is 36 Hence maximum product is 36  Input :          1                /   \               2     3              / \     \             4   5     8                      /  \                     6    7   Output :  160 Explanation : Product of all nodes of 0'th level is 1 Product of all nodes of 1'th level is 6 Product of all nodes of 2'th level is 160 Product of all nodes of 3'th level is 42 Hence maximum product is 160

Prerequisites: Maximum Width of a Binary Tree 

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Approach : The idea is to do level order traversal of tree. While doing traversal, process nodes of different level separately. For every level being processed, compute product of nodes in the level and keep track of maximum product. 

Implementation:

C++




// A queue based C++ program to find maximum product
// of a level in Binary Tree
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
    int data;
    struct Node *left, *right;
};
 
// Function to find the maximum product of a level in tree
// using level order traversal
int maxLevelProduct(struct Node* root)
{
    // Base case
    if (root == NULL)
        return 0;
 
    // Initialize result
    int result = root->data;
 
    // Do Level order traversal keeping track of number
    // of nodes at every level.
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
 
        // Get the size of queue when the level order
        // traversal for one level finishes
        int count = q.size();
 
        // Iterate for all the nodes in the queue currently
        int product = 1;
        while (count--) {
 
            // Dequeue an node from queue
            Node* temp = q.front();
            q.pop();
 
            // Multiply this node's value to current product.
            product = product * temp->data;
 
            // Enqueue left and right children of
            // dequeued node
            if (temp->left != NULL)
                q.push(temp->left);
            if (temp->right != NULL)
                q.push(temp->right);
        }
 
        // Update the maximum node count value
        result = max(product, result);
    }
 
    return result;
}
 
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
// Driver code
int main()
{
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->right = newNode(8);
    root->right->right->left = newNode(6);
    root->right->right->right = newNode(7);
 
    /* Constructed Binary tree is:
             1
            / \
           2   3
          / \   \
         4   5   8
                / \
               6   7 */
    cout << "Maximum level product is "
         << maxLevelProduct(root) << endl;
    return 0;
}
 
 

Java




// A queue based Java program to find
// maximum product of a level in Binary Tree
import java.util.*;
 
class GFG
{
 
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
static class Node
{
    int data;
    Node left, right;
};
 
// Function to find the maximum product
// of a level in tree using
// level order traversal
static int maxLevelProduct(Node root)
{
    // Base case
    if (root == null)
        return 0;
 
    // Initialize result
    int result = root.data;
 
    // Do Level order traversal keeping track
    // of number of nodes at every level.
    Queue<Node> q = new LinkedList<>();
    q.add(root);
    while (q.size() > 0)
    {
 
        // Get the size of queue when the level order
        // traversal for one level finishes
        int count = q.size();
 
        // Iterate for all the nodes
        // in the queue currently
        int product = 1;
        while (count-->0)
        {
 
            // Dequeue an node from queue
            Node temp = q.peek();
            q.remove();
 
            // Multiply this node's value
            // to current product.
            product = product* temp.data;
 
            // Enqueue left and right children of
            // dequeued node
            if (temp.left != null)
                q.add(temp.left);
            if (temp.right != null)
                q.add(temp.right);
        }
 
        // Update the maximum node count value
        result = Math.max(product, result);
    }
    return result;
}
 
/* Helper function that allocates
a new node with the given data and
null left and right pointers. */
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Driver code
public static void main(String args[])
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.right = newNode(8);
    root.right.right.left = newNode(6);
    root.right.right.right = newNode(7);
 
    /* Constructed Binary tree is:
            1
            / \
        2 3
        / \ \
        4 5 8
                / \
            6 7 */
    System.out.print("Maximum level product is " +
                          maxLevelProduct(root) );
}
}
 
// This code is contributed by Arnub Kundu
 
 

Python3




# Python3 program to find maximum product
# of a level in Binary Tree
 
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.                                    
class newNode:
 
    # Construct to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# Function to find the maximum product
# of a level in tree using level order
# traversal
def maxLevelProduct(root):
 
    # Base case
    if (root == None):
        return 0
 
    # Initialize result
    result = root.data
 
    # Do Level order traversal keeping track
    # of number of nodes at every level.
    q = []
    q.append(root)
    while (len(q)):
 
        # Get the size of queue when the level
        # order traversal for one level finishes
        count = len(q)
 
        # Iterate for all the nodes in
        # the queue currently
        product = 1
        while (count):
            count -= 1
             
            # Dequeue an node from queue
            temp = q[0]
            q.pop(0)
 
            # Multiply this node's value to
            # current product.
            product = product * temp.data
 
            # Enqueue left and right children
            # of dequeued node
            if (temp.left != None):
                q.append(temp.left)
            if (temp.right != None):
                q.append(temp.right)
         
        # Update the maximum node count value
        result = max(product, result)
     
    return result
 
# Driver Code
if __name__ == '__main__':
     
    """
    Let us create Binary Tree
    shown in above example """
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(3)
    root.left.left = newNode(4)
    root.left.right = newNode(5)
    root.right.right = newNode(8)
    root.right.right.left = newNode(6)
    root.right.right.right = newNode(7)
     
    """ Constructed Binary tree is:
            1
            / \
        2 3
        / \ \
        4 5 8
                / \
            6 7 """
 
    print("Maximum level product is",
               maxLevelProduct(root))
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
 
 

C#




// A queue based C# program to find
// maximum product of a level in Binary Tree
using System;
using System.Collections.Generic;
 
class GFG
{
 
    /* A binary tree node has data,
    pointer to left child and a
    pointer to right child */
    class Node
    {
        public int data;
        public Node left, right;
    };
 
    // Function to find the maximum product
    // of a level in tree using
    // level order traversal
    static int maxLevelProduct(Node root)
    {
        // Base case
        if (root == null)
        {
            return 0;
        }
 
        // Initialize result
        int result = root.data;
 
        // Do Level order traversal keeping track
        // of number of nodes at every level.
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        while (q.Count > 0)
        {
 
            // Get the size of queue when the level order
            // traversal for one level finishes
            int count = q.Count;
 
            // Iterate for all the nodes
            // in the queue currently
            int product = 1;
            while (count-- > 0)
            {
 
                // Dequeue an node from queue
                Node temp = q.Peek();
                q.Dequeue();
 
                // Multiply this node's value
                // to current product.
                product = product * temp.data;
 
                // Enqueue left and right children of
                // dequeued node
                if (temp.left != null)
                {
                    q.Enqueue(temp.left);
                }
                if (temp.right != null)
                {
                    q.Enqueue(temp.right);
                }
            }
 
            // Update the maximum node count value
            result = Math.Max(product, result);
        }
        return result;
    }
 
    /* Helper function that allocates
    a new node with the given data and
    null left and right pointers. */
    static Node newNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = node.right = null;
        return (node);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        Node root = newNode(1);
        root.left = newNode(2);
        root.right = newNode(3);
        root.left.left = newNode(4);
        root.left.right = newNode(5);
        root.right.right = newNode(8);
        root.right.right.left = newNode(6);
        root.right.right.right = newNode(7);
 
        /* Constructed Binary tree is:
            1
            / \
        2 3
        / \ \
        4 5 8
                / \
            6 7 */
        Console.Write("Maximum level product is " +
                            maxLevelProduct(root));
    }
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
// A queue based Javascript program to find
// maximum product of a level in Binary Tree
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
class Node
{
    constructor()
    {
        this.left = null;
        this.right = null;
        this.data = 0;
    }
};
 
// Function to find the maximum product
// of a level in tree using
// level order traversal
function maxLevelProduct(root)
{
    // Base case
    if (root == null)
    {
        return 0;
    }
    // Initialize result
    var result = root.data;
    // Do Level order traversal keeping track
    // of number of nodes at every level.
    var q = [];
    q.push(root);
    while (q.length > 0)
    {
        // Get the size of queue when the level order
        // traversal for one level finishes
        var count = q.length;
        // Iterate for all the nodes
        // in the queue currently
        var product = 1;
        while (count-- > 0)
        {
            // Dequeue an node from queue
            var temp = q[0];
            q.shift();
            // Multiply this node's value
            // to current product.
            product = product * temp.data;
            // push left and right children of
            // dequeued node
            if (temp.left != null)
            {
                q.push(temp.left);
            }
            if (temp.right != null)
            {
                q.push(temp.right);
            }
        }
        // Update the maximum node count value
        result = Math.max(product, result);
    }
    return result;
}
/* Helper function that allocates
a new node with the given data and
null left and right pointers. */
function newNode(data)
{
    var node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Driver code
var root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.right = newNode(8);
root.right.right.left = newNode(6);
root.right.right.right = newNode(7);
/* Constructed Binary tree is:
    1
    / \
2 3
/ \ \
4 5 8
        / \
    6 7 */
document.write("Maximum level product is " +
                    maxLevelProduct(root));
 
// This code is contributed by famously.
</script>
 
 
Output
Maximum level product is 160

Complexity Analysis:

  • Time Complexity : O(n) 
  • Auxiliary Space : O(n) 


Next Article
Find maximum level sum in Binary Tree
author
bansal_rtk_
Improve
Article Tags :
  • DSA
  • Recursion
  • Tree
  • cpp-queue
  • tree-level-order
Practice Tags :
  • Recursion
  • Tree

Similar Reads

  • Find maximum level sum in Binary Tree
    Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6Output: 6Explanation :Sum of all nodes of 0'th level is 4Sum of all nodes of 1'th level is -3Sum of all nodes of 0'th level is 6Hence maximum sum is 6
    15+ min read
  • Find the maximum node at a given level in a binary tree
    Given a Binary Tree and a Level. The task is to find the node with the maximum value at that given level. The idea is to traverse the tree along depth recursively and return the nodes once the required level is reached and then return the maximum of left and right subtrees for each subsequent call.
    13 min read
  • Maximum product of any path in given Binary Tree
    Given a binary tree of N nodes, the task is to find the maximum product of the elements of any path in the binary tree. Note: A path starts from the root and ends at any leaf in the tree. Examples: Input: 4 / \ 2 8 / \ / \2 1 3 4 Output: 128Explanation: Path in the given tree goes like {4, 8, 4} whi
    5 min read
  • Find maximum vertical sum in binary tree
    Given a binary tree, find the maximum vertical level sum in binary tree. Examples: Input : 3 / \ 4 6 / \ / \ -1 -2 5 10 \ 8 Output : 14Vertical level having nodes 6 and 8 has maximumvertical sum 14. Input : 1 / \ 5 8 / \ \ 2 -6 3 \ / -1 -4 \ 9Output : 4 A simple solution is to first find vertical le
    9 min read
  • Find the level with maximum setbit count in given Binary Tree
    Given a binary tree having N nodes, the task is to find the level having the maximum number of setbits. Note: If two levels have same number of setbits print the one which has less no of nodes. If nodes are equal print the first level from top to bottom Examples: Input: 2 / \ 5 3 / \6 1Output: 2Expl
    11 min read
  • Finding Minimum Steps in Special Binary Tree
    Given two integer values (i and j) as input representing two nodes of a special binary tree. The special binary tree has this property that the root node's value is always 1 and for every node, its left child will be the node's value * 3, and the right child will be ( node's value * 3) + 1. The give
    8 min read
  • Find the sum of leafs at maximum level
    Given a binary tree containing n nodes. The task is to find the sum of all the leaf nodes present at maximum level.Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 Output: 17 Leaf nodes 8 and 9 are at maximum level. Their sum = (8 + 9) = 17. Input: 5 / \ 8 13 / 4 Output: 4 Approach: Perform iterat
    9 min read
  • Product of all nodes in a Binary Tree
    Given a Binary Tree. The task is to write a program to find the product of all of the nodes of the given binary tree. In the above binary tree, Product = 15*10*8*12*20*16*25 = 115200000 The idea is to recursively: Find the product of the left subtree.Find the product of the right subtree.Multiply th
    6 min read
  • Min-Max Product Tree of a given Binary Tree
    Given a Binary Tree, the task is to convert the given Binary tree into Min-Max Product Tree and print the level-order sequence of the modified tree. Min-Max Product Tree: A Min-Max Product Tree contains the product of the minimum and maximum values of its left and right subtrees at each node. Note:
    14 min read
  • Find Minimum Depth of a Binary Tree
    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences