- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find maximum level product in Binary Tree in C++
Suppose, one binary tree is given. It has positive and negative nodes. We have to find the maximum product at each level of it.
Consider this is the tree, so the product of level 0 is 4, product of level 1 is 2 * -5 = -10, and product of level 2 is -1 * 3 * -2 * 6 = 36. So this is the maximum one.
To solve this, we will perform the level order traversal of the tree, during traversal, process doing the nodes of different levels separately. Then get the maximum product.
Example
#include<iostream> #include<queue> using namespace std; class Node { public: int data; Node *left, *right; }; Node* getNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } int getMaxLevelProduct(Node* root) { if (root == NULL) return 0; int res = root->data; queue<Node*> q; q.push(root); while (!q.empty()) { int count = q.size(); int prod = 1; while (count--) { Node* temp = q.front(); q.pop(); prod *= temp->data; if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } res = max(prod, res); } return res; } int main() { Node* root = getNode(4); root->left = getNode(2); root->right = getNode(-5); root->left->left = getNode(-1); root->left->right = getNode(3); root->right->left = getNode(-2); root->right->right = getNode(6); cout << "Maximum level product is " << getMaxLevelProduct(root) << endl; }
Output
Maximum level product is 36
Advertisements