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 the parent node of maximum product Siblings in given Binary Tree
Next article icon

Maximum product of any path in given Binary Tree

Last Updated : 04 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 128
Explanation: Path in the given tree goes like {4, 8, 4} which gives the max score of 4 x 8 x 4 = 128.

Input:
    10
  /    \
7      5
         \
          1

Output: 70 
Explanation: The path {10, 7} gives a score of 70 which is the maximum possible.

 

Approach: The idea to solve the problem is by using DFS traversal of a tree using recursion.

For every node recursively find the maximum product of left subtree and right subtree of that node and return the product of that value with the node’s data.

Follow the steps mentioned below to solve the problem

  • As the base Condition. If the root is NULL, simply return 1.
  • Call the recursive function for the left and right subtrees to get the maximum product from both the subtrees.
  • Return the value of the current node multiplied by the maximum product out of the left and right subtree as the answer of the current recursion.

Below is the implementation of the above approach.

C++




// C++ code for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a tree Node
struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val) { this->data = val; }
};
 
// Utility function to create a new Tree Node
long long findMaxScore(Node* root)
{
    // Base Condition
    if (root == 0)
        return 1;
 
    // max product path = root->data
    // multiplied by max of
    // max_product_path of left subtree
    // and max_product_path
    // of right subtree
    return root->data
           * max(findMaxScore(root->left),
                 findMaxScore(root->right));
}
 
// Driver Code
int main()
{
    Node* root = new Node(4);
    root->left = new Node(2);
    root->right = new Node(8);
    root->left->left = new Node(3);
    root->left->right = new Node(1);
    root->right->left = new Node(3);
    root->right->right = new Node(4);
 
    // Function call
    cout << findMaxScore(root) << endl;
    return 0;
}
 
 

Java




// Java code for the above approach:
import java.util.*;
class GFG
{
 
  // Structure of a tree Node
  public static class Node {
    int data;
    Node left;
    Node right;
    Node(int val) { this.data = val; }
  }
 
  // Utility function to create a new Tree Node
  public static long findMaxScore(Node root)
  {
    // Base Condition
    if (root == null)
      return 1;
 
    // Mmax product path = root.data
    // multiplied by max of
    // max_product_path of left subtree
    // and max_product_path
    // of right subtree
    return root.data
      * Math.max(findMaxScore(root.left),
                 findMaxScore(root.right));
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    Node root = new Node(4);
    root.left = new Node(2);
    root.right = new Node(8);
    root.left.left = new Node(3);
    root.left.right = new Node(1);
    root.right.left = new Node(3);
    root.right.right = new Node(4);
 
    // Function call
    System.out.println(findMaxScore(root));
  }
}
 
// This code is contributed by Taranpreet
 
 

Python3




# Python code for the above approach
 
# Structure of a tree Node
class Node:
    def __init__(self,d):
        self.data = d
        self.left = None
        self.right = None
 
# Utility function to create a new Tree Node
def findMaxScore(root):
 
    # Base Condition
    if (root == None):
        return 1
 
    # Mmax product path = root->data
    # multiplied by max of
    # max_product_path of left subtree
    # and max_product_path
    # of right subtree
    return root.data * max(findMaxScore(root.left),findMaxScore(root.right))
 
# Driver Code
root = Node(4)
root.left = Node(2)
root.right = Node(8)
root.left.left = Node(3)
root.left.right = Node(1)
root.right.left = Node(3)
root.right.right = Node(4)
 
# Function call
print(findMaxScore(root))
 
# This code is contributed by shinjanpatra
 
 

C#




// C# code to implement the approach
using System;
 
class GFG
{
 
  // Structure of a tree Node
  public class Node {
    public int data;
    public Node left;
    public Node right;
    public Node(int val) { this.data = val; }
  }
 
  // Utility function to create a new Tree Node
  public static long findMaxScore(Node root)
  {
    // Base Condition
    if (root == null)
      return 1;
 
    // Mmax product path = root.data
    // multiplied by max of
    // max_product_path of left subtree
    // and max_product_path
    // of right subtree
    return root.data
      * Math.Max(findMaxScore(root.left),
                 findMaxScore(root.right));
  }
 
// Driver Code
public static void Main()
{
    Node root = new Node(4);
    root.left = new Node(2);
    root.right = new Node(8);
    root.left.left = new Node(3);
    root.left.right = new Node(1);
    root.right.left = new Node(3);
    root.right.right = new Node(4);
 
    // Function call
    Console.WriteLine(findMaxScore(root));
}
}
 
// This code is contributed by jana_sayantan.
 
 

Javascript




<script>
       // JavaScript code for the above approach
 
       // Structure of a tree Node
       class Node
       {
           constructor(d)
           {
               this.data = d;
               this.left = null;
               this.right = null;
           }
       };
 
       // Utility function to create a new Tree Node
       function findMaxScore(root)
       {
        
           // Base Condition
           if (root == null)
               return 1;
 
           // Mmax product path = root->data
           // multiplied by max of
           // max_product_path of left subtree
           // and max_product_path
           // of right subtree
           return root.data
               * Math.max(findMaxScore(root.left),
                   findMaxScore(root.right));
       }
 
       // Driver Code
       let root = new Node(4);
       root.left = new Node(2);
       root.right = new Node(8);
       root.left.left = new Node(3);
       root.left.right = new Node(1);
       root.right.left = new Node(3);
       root.right.right = new Node(4);
 
       // Function call
       document.write(findMaxScore(root) + '<br>');
 
     // This code is contributed by Potta Lokesh
   </script>
 
 

 
 

Output
128

 

Time Complexity: O(N).
Auxiliary Space: O( Height of the tree)

 



Next Article
Find the parent node of maximum product Siblings in given Binary Tree
author
ishankhandelwals
Improve
Article Tags :
  • DSA
  • Geeks Premier League
  • Tree
  • DFS
  • Geeks-Premier-League-2022
Practice Tags :
  • DFS
  • Tree

Similar Reads

  • Maximum Path Sum in a Binary Tree
    Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree. Example: Input: Output: 42Explanation: Max path sum is represented using green colour nodes in the above binary tree. Input: Output: 31Explanation: Max path sum is represented using gre
    9 min read
  • Maximum product of two non-intersecting paths in a tree
    Given an undirected connected tree with N nodes (and N-1 edges), we need to find two paths in this tree such that they are non-intersecting and the product of their length is maximum. Examples: In first tree two paths which are non-intersecting and have highest product are, 1-2 and 3-4, so answer is
    12 min read
  • Find the parent node of maximum product Siblings in given Binary Tree
    Given a binary tree, the task is to find the node whose children have maximum Sibling product in the given Binary Tree. If there are multiple such nodes, return the node which has the maximum value. Examples: Input: Tree: 4 / \ 5 2 / \ 3 1 / \6 12Output: 3Explanation: For the above tree, the maximum
    15+ min read
  • Find maximum level product in Binary Tree
    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 H
    9 min read
  • Find the maximum sum leaf to root path in a Binary Tree
    Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root. Example : Input: Output: 60Explanantion: There are three leaf to root paths 20->30->10, 5->30->10 and 15->10. The sums of these three paths are 60, 45 and 25 respectively. The maximum of them is 60 an
    15+ min read
  • Maximum Path sum in a N-ary Tree
    Given an undirected tree with n nodes numbered from 1 to n and an array arr[] where arr[i] denotes the value assigned to (i+1)th node. The connections between the nodes are provided in a 2-dimensional array edges[][]. The task is to find the maximum path sum between any two nodes. (Both the nodes ca
    7 min read
  • Maximum XOR path of a Binary Tree
    Given a Binary Tree, the task is to find the maximum of all the XOR value of all the nodes in the path from the root to leaf.Examples: Input: 2 / \ 1 4 / \ 10 8 Output: 11 Explanation: All the paths are: 2-1-10 XOR-VALUE = 9 2-1-8 XOR-VALUE = 11 2-4 XOR-VALUE = 6 Input: 2 / \ 1 4 / \ / \ 10 8 5 10 O
    8 min read
  • Sum and Product of maximum and minimum element in Binary Tree
    Given a Binary Tree. The task is to find the sum and product of the maximum and minimum elements in it. For example, sum of the maximum and minimum elements in the following binary tree is 10 and the product is 9. The idea is to traverse the tree and find the maximum and minimum elements in the tree
    12 min read
  • Maximum parent children sum in Binary tree
    Given a Binary Tree, find the maximum sum in a binary tree by adding the parent with its children. Exactly three Node needs to be added. If the tree does not have a node with both of its children as not NULL, return 0. We simply traverse the tree and find the Node that has the maximum sum. We need t
    5 min read
  • Maximum in a Binary Search Tree
    Given a Binary Search Tree, the task is to find the node with the maximum value in a BST. Example: Input: Output : 7 Input: Output: 20 Table of Content [Naive Approach] Using Inorder Traversal – O(n) Time and O(n) Space[Expected Approach] Iterative Approach – O(n) Time and O(1) Space[Naive Approach]
    11 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