Maximum Level Sum of a Binary Tree in C++

C++Server Side ProgrammingProgramming

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 < sum, then ansSum := sum, ansLevel := level
  • return ansLevel

Example

Let us see the following implementation to get better understanding −

class Solution {
public:
   int maxLevelSum(TreeNode* r) {
      int level = 1, sum = r->val;
      int ansLevel = level, ansSum = sum;
      queue <TreeNode*> 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<sum){
            ansSum = sum;
            ansLevel = level;
         }
      }
      return ansLevel;
   }
};

Input

[1,7,0,7,-8,null,null]

Output

2
raja
Published on 17-Mar-2020 10:26:18
Advertisements