Max Level Sum in Binary Tree | Practice | GeeksforGeeks

Given a Binary Tree having positive and negative nodes. Find the maximum sum of a level in the given Binary Tree.
Example 1:
Input :               
             4
          /    \
         2     -5
        / \    / \
      -1   3  -2  6

Output: 6

Explanation :
Sum of all nodes of 0'th level is 4
Sum of all nodes of 1'th level is -3
Sum of all nodes of 2'th level is 6
Hence maximum sum is 6

Example 2:
Input :          
            1
          /   \
         2     3
        / \     \
       4   5     8
                / \
               6   7  

Output :  17

Explanation: Maximum sum is at level 2.

Your Task:  
You dont need to read input or print anything. Complete the function maxLevelSum() which takes root node as input parameter and returns the maximum sum of any horizontal level in the given Binary Tree.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

Constraints:
1 ≤ N ≤ 104
0
harshscode1 week ago
 vector<int> v;       queue<Node*> q;       q.push(root);              while(!q.empty())       {           int n=q.size();           int sum=0;           while(n--)           {               Node *temp=q.front();               q.pop();               int p=temp->data;               sum+=p;                             if(temp->left)               q.push(temp->left);               if(temp->right)               q.push(temp->right);                                                        }           v.push_back(sum);       }              int maxx=v[0];       for(int i=0;i<v.size();i++)       {           if(v[i]>maxx)           maxx=v[i];       }              return maxx;
0
detroix071 month ago
class Solution { public:   /*You are required to complete below method */   int maxLevelSum(Node* root) {       queue<Node*> q;       q.push(root);       q.push(NULL);       int sum = 0;       int max=INT_MIN;              while(q.size()!=0) {        Node* Front = q.front();        q.pop();        if(Front==NULL) {         if(sum>max) max=sum;         sum=0;         if(q.size()==0) break;         q.push(NULL);        } else {          sum+=Front->data;          if(Front->left!=NULL) q.push(Front->left);          if(Front->right!=NULL) q.push(Front->right);        }     }     return max;   }};
0
namanshah22752 months ago
SHORT SOLUTION : TIME O(N) 
0.4 sec
 
 int maxLevelSum(Node* root) {              queue<Node*> q;       int ans = INT_MIN;       int newans;              q.push(root);       while(!q.empty())       {           newans = 0;           int n = q.size();                      while(n--)           {               Node* p = q.front();               newans = newans + p->data;               q.pop();                              if(p->left)               q.push(p->left);                              if(p->right)               q.push(p->right);                          }                      if(newans > ans)           ans = newans;       }              return ans;   }}; 
0
owaischem3 months ago
PYTHON SOLUTION:
TIME TAKEN:12.7/15.5
(time taken is high due to the use of recursion)
 
class Solution:   def maxLevelSum(self, root):       def height(root):           if root==None:               return 0                          left=height(root.left)           right=height(root.right)                      return max(left,right)+1                  def level_traversal(root,level):           if root==None:               return None           elif level==0:               list1.append(root.data)           else:               level_traversal(root.left,level-1)               level_traversal(root.right,level-1)                      tall=height(root)       maximum=-9999999       list1=[]       for i in range(tall):           level_traversal(root,i)           maximum=max(maximum,sum(list1))           list1=[]                  return maximum
0
bhushan5613 months ago
SIMPLEST CPP SOLUTION
TIME COMPLEXITY-O(N)
 
 
int maxLevelSum(Node* root) {       // Your code here       vector<int>ans;       queue<Node*>q;       q.push(root);       while(!q.empty())       {           int sum=0;           int n=q.size();           for(int i=0;i<n;i++)           {               auto temp=q.front();               q.pop();               if(temp->left)               q.push(temp->left);               if(temp->right)               q.push(temp->right);               sum=sum+temp->data;           }           ans.push_back(sum);       }       return *max_element(ans.begin(),ans.end());   }
0
anshwalgiri3 months ago
int maxLevelSum(Node* root)   {       Node * temp = root;       queue <Node *> nodeQ;       int sum = 0, prior_sum=INT_MIN, result, count =0;              if (temp == NULL)           return -1;              nodeQ.push(temp);       while (nodeQ.empty() == false)       {           sum = 0;           count = nodeQ.size();           while (count--)           {               Node *node = nodeQ.front();               sum += node -> data;               nodeQ.pop();                              if (node -> left != NULL)                   nodeQ.push(node -> left );               if (node -> right != NULL)                   nodeQ.push(node -> right );           }                      result = max (sum, prior_sum);           // Keep max value here           prior_sum = result;       }       return result;   }
0
abhishekvicky123453 months ago
/*Java Solution*/
 
class Solution {   public int max=-1000;   public void odd(Stack<Node> s1,Stack<Node> s2)   {       Node temp;       int sum=0;       while(s1.size()>0)       {           temp=s1.pop();           sum=sum+temp.data;           if(temp.left!=null)           s2.add(temp.left);           if(temp.right!=null)           s2.add(temp.right);       }       if(sum>max)max=sum;       if(s2.size()>0)       even(s1,s2);   }      public void even(Stack<Node> s1,Stack<Node> s2)   {       Node temp;int sum=0;       while(s2.size()>0)       {           temp=s2.pop();           sum=sum+temp.data;           if(temp.left!=null)           s1.add(temp.left);           if(temp.right!=null)           s1.add(temp.right);       }       if(sum>max)max=sum;       if(s1.size()>0)       odd(s1,s2);   }         public int maxLevelSum(Node root) {       Stack<Node> s1=new Stack<>();       Stack<Node> s2=new Stack<>();       if(root==null) return 0;       s1.add(root);       odd(s1,s2);       return max;   }}
+1
kronizerdeltac3 months ago
JAVA SOLUTION - BFS
 
public int maxLevelSum(Node root) {       if(root == null)           return -1;
       LinkedList<Node> queue = new LinkedList<>();       queue.addLast(root);       int maxSum = -(int) 1e9;
       while(queue.size() != 0) {           int size = queue.size(), sum = 0;           while(size-- > 0) {               Node rnode = queue.removeFirst();               sum += rnode.data;
               if(rnode.left != null)                   queue.addLast(rnode.left);               if (rnode.right != null)                   queue.addLast(rnode.right);
           }           if(sum > maxSum)               maxSum = sum;       }       return maxSum;   }
0
mayank20213 months ago
c++class Solution{ public:   /*You are required to complete below method */   int maxLevelSum(Node* root) {   int max=INT_MIN;   vector<int> levelsum;   lsum(root, 1, levelsum);      for(auto i:levelsum)    {        if(max<i)         max=i;    }
   return max;   } public:   void lsum(Node* root, int l,vector<int> &levelsum )   {       if(root)        {            if(levelsum.size() < l)               levelsum.push_back(root->data);            else               levelsum[l-1]=levelsum[l-1]+root->data;                        lsum(root->left, l+1, levelsum);            lsum(root->right, l+1, levelsum);                           }  } };
0
riyu20223 months ago
SIMPLE PYTHON ITERATIVE
class Solution:
    def maxLevelSum(self, root):
        # Code here
        if not root:
            return False
        ans = []
        res = []
        q = deque([root])
        while q:
            level = []
            for _ in range(len(q)):
                node = q.popleft()
                level.append(node.data)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            ans.append(level)
        for a in ans:
            res.append(sum(a))
        return max(res)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.