Advertisement
jayati

Maximum Level Sum of a Binary Tree

May 15th, 2024
500
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     queue<pair<int,int>> q;
  15.     int mxl=INT_MIN;
  16.     int maxLevelSum(TreeNode* root)
  17.     {
  18.         if(root==NULL)
  19.         {
  20.             return root->val;
  21.         }
  22.         recursion(root,0);
  23.         vector<int> v(mxl+1,0);
  24.         while(!q.empty())
  25.         {
  26.            
  27.             int fir=q.front().first;
  28.             int sec=q.front().second;
  29.             v[sec]+=fir;
  30.             q.pop();
  31.         }
  32.         int mx=INT_MIN;
  33.         int ans=-1;
  34.         for(int i=0;i<v.size();i++)
  35.         {
  36.             if(v[i]>mx)
  37.             {
  38.                 mx=v[i];
  39.                 ans=i;
  40.             }
  41.         }
  42.         return ans+1;
  43.     }
  44.     void recursion(TreeNode* root,int level)
  45.     {
  46.            if(root==NULL)
  47.            {
  48.             return;
  49.            }
  50.            mxl=max(mxl,level);
  51.            q.push({root->val,level});
  52.            recursion(root->left,level+1);
  53.            recursion(root->right,level+1);
  54.            
  55.     }
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement