News Leaflets
A leading news portal.

Maximum product of any path in given Binary Tree

0 67

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.


        /   \
     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.

  /    \
7      5

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 substree 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.



#include <bits/stdc++.h>

using namespace std;


struct Node {

    int data;

    Node* left;

    Node* right;

    Node(int val) { this->data = val; }



long long findMaxScore(Node* root)



    if (root == 0)

        return 1;







    return root->data

           * max(findMaxScore(root->left),




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);



    cout << findMaxScore(root) << endl;

    return 0;


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


Read original article here

Denial of responsibility! News Leaflets is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave a comment