Diagonal Sum In Binary Tree | Practice | GeeksforGeeks

Consider Red lines of slope -1 passing between nodes (in following diagram). The diagonal sum in a binary tree is the sum of all node’s data lying between these lines. Given a Binary Tree of size N, print all diagonal sums.
For the following input tree, output should be 9, 19, 42.
9 is sum of 1, 3 and 5.
19 is sum of 2, 6, 4 and 7.
42 is sum of 9, 10, 11 and 12.
Example 1:
Input:
         4
       /   \
      1     3
           /
          3
Output: 7 4 

Example 2:
Input:
           10
         /    \
        8      2
       / \    /
      3   5  2
Output: 12 15 3 

Your Task:
You don't need to take input. Just complete the function diagonalSum() that takes root node of the tree as parameter and returns an array containing the diagonal sums for every diagonal present in the tree with slope -1.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1<=Number of nodes<=105

Note: The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
+2
forcer2 months ago
vector<int>v;   if(!root) return {};   queue<Node*>q;   q.push(root);   while(!q.empty())   {       int n=q.size();       int sum=0;       for(int i=0;i<n;i++)       {           Node *t=q.front();q.pop();                      while(t)           {                  sum+=t->data;               if(t->left) q.push(t->left);               t=t->right;           }       }       v.push_back(sum);   }   return v;
 
0
sufyankhan96782 months ago
void help(vector<int>&v,Node* root,int start){
    
    if(root==nullptr) return;
    int dt=root->data;
    if(v.size()+1==start) v.push_back(dt);
    else if(v.size()>=start) v[start-1]+=dt;
    
    if(root->left!=nullptr){
        help(v,root->left,start+1);
    }
    if(root->right!=nullptr){
        help(v,root->right,start);
    }
    
}
vector <int> diagonalSum(Node* root) {
    vector<int>v;
    help(v,root,1);
    return v;
}
0
rahulroy123 months ago
void di(Node *root, map<int,int,greater<int>>&mp, int l ){   if(!root)return;      mp[l]+=root->data;   di(root->left,mp,l-1);   di(root->right,mp,l);}vector <int> diagonalSum(Node* root) {         map<int,int,greater<int>>mp;   vector<int>v;   di(root,mp,0);   for(auto it:mp){       v.push_back(it.second);   }   return v;}
0
abrajput15063 months ago
void dSum(Node* root,int d,vector<int> &v){   if(!root)       return;   if(!root->left && !root->right){       v[d] += root->data;        return;   }   //cout<<d<<" "<<root->data<<endl;   v[d] += root->data;   dSum(root->left,d+1,v);   dSum(root->right,d,v);   }int noOfDiagonal(Node* root,int d){   if(!root)       return d;   return max(noOfDiagonal(root->left,d+1),noOfDiagonal(root->right,d));}vector <int> diagonalSum(Node* root) {   // Add your code here   int n = noOfDiagonal(root,0);   vector<int> v(n);   for(int i=0;i<n;i++)       v[i] =0;   dSum(root,0,v);   return v;}
0
shubhamvast53 months ago
We can solve it by using 2 queue by following method
 public static ArrayList <Integer> diagonalSum(Node root) 
   {
        ArrayList<Integer> list = new ArrayList<>();
       if (root == null)
           return list;
       Queue<Node> q1 = new LinkedList<>();
       Queue<Node> q2 = new LinkedList<>();
       q1.offer(root);
       while (!q1.isEmpty())
       {
           int sum = 0;
           while (!q1.isEmpty())
           {
               Node n = q1.poll();
               if(n.right != null)
                   q1.offer(n.right);
               sum += n.data;
               q2.offer(n);
           }
           list.add(sum);
           while (!q2.isEmpty())
           {
               Node n = q2.poll();
               if (n.left != null)
                   q1.offer(n.left);
           }
       }
       return list;
   }
0
aharshit3503 months ago
JAVA :EASIEST
 LinkedList<Node>q=new LinkedList<>();       ArrayList<Integer>list=new ArrayList<>();        if(root==null)list.add(0);       q.add(root);       while(!q.isEmpty()){           ArrayList<Integer>small=new ArrayList<>();           int size=q.size();           int res=0;           while(size-->0){               Node rn=q.removeFirst();               while(rn!=null){                   small.add(rn.data);                   if(rn.left!=null)q.add(rn.left);                   rn=rn.right;               }           }for(int i=0;i<small.size();i++){                   res+=small.get(i);               }list.add(res);       }return list;
0
17vineet
This comment was deleted.
0
nekhatperveen3 months ago
JAVA
  public static ArrayList <Integer> diagonalSum(Node root)    {         ArrayList<Integer> arrList = new ArrayList<>();     int level = 0;     calculateSum(arrList, level, root);     return arrList;          }  static void calculateSum(ArrayList<Integer> arrList, int level, Node root)   {       if(root==null)           return;       else       {           if(arrList.size()<level+1)           {               arrList.add(root.data);           }           else           {               int oldSum = arrList.get(level);               arrList.set(level, oldSum+ root.data);           }
           calculateSum(arrList, level, root.right);           calculateSum(arrList, level + 1, root.left);       }   }
+1
radheshyamnitj3 months ago
queue<Node*>q;
  vector<int>ans;
  if(!root) return ans;
  q.push(root);
  q.push(NULL);
  int sum=0;
   
  while(!q.empty()){
    
      if(q.front()==NULL)
      {
          ans.push_back(sum);
          sum=0;
          q.push(NULL);
          q.pop();
      }
      
      Node *temp=q.front();
      q.pop();

      while(temp){
          sum+=temp->data;
          if(temp->left) q.push(temp->left);
          temp=temp->right;
      }
  }
+3
imsaiful6 months ago
Soln of Problem:
think like when we go to left it will start a new diagonal. 
Right side will continue for same diagonal and add them. 
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.