Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Maximum Level Sum of a Binary Tree in C++
Suppose we have the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. We have to return the smallest level X such that the sum of all the values of nodes at level X is maximal. So if the tree is like −

Then the output will be 2, The level 1 sum = 1, level 2 sum is 7 + 0 = 7, level 2 sum is 7 + (-8) = -1, so max is of level 2, so output is 2.
To solve this, we will follow these steps −
- level := 1, sum := value of r, ansLevel := level, ansSum := sum
- define a queue q, insert given node r into q
- while q is not empty
- capacity := size of q
- increase level by 1, sum := 0
- while capacity is not 0
- node := front node from q, delete node from q
- if right of node is valid, then sum := sum + value of right node, insert right node into q
- if left of node is valid, then sum := sum + value of left node, insert left node into q
- decrease capacity by 1
- if ansSum
- return ansLevel
Example(C++)
Let us see the following implementation to get a better understanding −
Live Demo Live Demo
#includeusing namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; } else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; } else{ q.push(temp->right); } } } TreeNode *make_tree(vector v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i val; int ansLevel = level, ansSum = sum; queue q; q.push(r); while(!q.empty()){ int capacity = q.size(); level++; sum = 0; while(capacity--){ TreeNode* node = q.front(); q.pop(); if(node->right){ sum += node->right->val; q.push(node->right); } if(node->left){ sum += node->left->val; q.push(node->left); } } if(ansSum v = {1,7,0,7,-8,NULL,NULL}; TreeNode *root = make_tree(v); Solution ob; cout Input
[1,7,0,7,-8,null,null]Output
2
Advertisements
