Diagonal Sum of a Binary Tree

Last Updated : 16 May, 2026

Consider lines passing between nodes (in the following diagram). The diagonal sum in a binary tree is the sum of all node data lying between these lines. Given a Binary Tree of size n, print all diagonal sums.

2056957878

For the following input tree, the output should be 9, 19, 42.
9 is the sum of 1, 3, and 5.
19 is the sum of 2, 6, 4, and 7.
42 is the sum of 9, 10, 11, and 12.

Examples:

Input:

blobid2_1777963613

Output: 7 4 
Explanation: Node 4 and its right child 3 lie on diagonal 0 giving sum 7,
and node 1 with its right child 3 lie on diagonal 1 giving sum 4.

Input:

blobid3_1777963680

Output: 12 15 3

Try It Yourself
redirect icon

Using Level − Index to Group Diagonals - O(n log n) Time O(n) Space

The idea is to group nodes based on (level - index), as nodes on the same diagonal have the same value. Start from the root with (0, 0), add each node’s value to grid [level - index], move left to the next diagonal, and right to the same diagonal. This groups and sums nodes diagonal-wise efficiently.

Let us understand with an example:
Start: grid = {}
Step-by-step traversal:

  • Node 10 -> (level = 0, index = 0) -> key = 0 -> grid = {0: 10}
  • Move left -> Node 8 -> (1, -1) -> key = 2 -> grid = {0: 10, 2: 8}
  • Move left -> Node 3 -> (2, -2) -> key = 4 -> grid = {0: 10, 2: 8, 4: 3}
  • Backtrack, move right -> Node 5 -> (2, 0) -> key = 2 -> grid = {0: 10, 2: 13, 4: 3}
  • Back to root, move right -> Node 2 -> (1, 1) -> key = 0 -> grid = {0: 12, 2: 13, 4: 3}
  • Move left -> Node 2 -> (2, 0) -> key = 2 -> grid = {0: 12, 2: 15, 4: 3}

Final grid: 0 -> 12, 2 -> 15, 4 -> 3 Output: 12 15 3

C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
public:
    int data;
    Node *left;
    Node *right;
    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

void dfs(Node *root, int level, int index, map<int, int> &mp)
{
    if (!root)
        return;

    // correct diagonal key = level - index
    mp[level - index] += root->data;

    // left → next diagonal
    dfs(root->left, level + 1, index - 1, mp);

    // right → same diagonal direction
    dfs(root->right, level + 1, index + 1, mp);
}

vector<int> diagonalSum(Node *root)
{
    map<int, int> mp;
    dfs(root, 0, 0, mp);

    vector<int> ans;
    for (auto &it : mp)
    {
        ans.push_back(it.second);
    }
    return ans;
}

// Driver code
int main()
{

    Node *root = new Node(10);
    root->left = new Node(8);
    root->right = new Node(2);

    root->left->left = new Node(3);
    root->left->right = new Node(5);

    root->right->left = new Node(2);

    vector<int> ans = diagonalSum(root);

    cout << "Diagonal sum in a binary tree is: ";

    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i] << " ";
    }

    return 0;
}
Java
import java.util.HashMap;
import java.util.ArrayList;

class Node {
    public int data;
    public Node left;
    public Node right;
    public Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

public class GfG {
    static void dfs(Node root, int level, int index, HashMap<Integer, Integer> mp) {
        if (root == null) return;

        // correct diagonal key = level - index
        mp.put(level - index, mp.getOrDefault(level - index, 0) + root.data);

        // left → next diagonal
        dfs(root.left, level + 1, index - 1, mp);

        // right → same diagonal direction
        dfs(root.right, level + 1, index + 1, mp);
    }

    static ArrayList<Integer> diagonalSum(Node root) {
        HashMap<Integer, Integer> mp = new HashMap<>();
        dfs(root, 0, 0, mp);

        ArrayList<Integer> ans = new ArrayList<>();
        for (int value : mp.values()) {
            ans.add(value);
        }
        return ans;
    }

    public static void main(String[] args) {
        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);

        root.left.left = new Node(3);
        root.left.right = new Node(5);

        root.right.left = new Node(2);

        ArrayList<Integer> ans = diagonalSum(root);

        System.out.print("Diagonal sum in a binary tree is: ");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i) + " ");
        }
    }
}
Python
from collections import defaultdict

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

def dfs(root, level, index, mp):
    if not root:
        return

    # correct diagonal key = level - index
    mp[level - index] += root.data

    # left → next diagonal
    dfs(root.left, level + 1, index - 1, mp)

    # right → same diagonal direction
    dfs(root.right, level + 1, index + 1, mp)

def diagonalSum(root):
    mp = defaultdict(int)
    dfs(root, 0, 0, mp)

    ans = []
    for key in sorted(mp):
        ans.append(mp[key])
    return ans

# Driver code
if __name__ == '__main__':
    root = Node(10)
    root.left = Node(8)
    root.right = Node(2)

    root.left.left = Node(3)
    root.left.right = Node(5)

    root.right.left = Node(2)

    ans = diagonalSum(root)

    print('Diagonal sum in a binary tree is:', end=' ')
    for i in ans:
        print(i, end=' ')
C#
using System;
using System.Collections.Generic;

public class Node
{
    public int data;
    public Node left;
    public Node right;
    public Node(int val)
    {
        data = val;
        left = null;
        right = null;
    }
}

public class GfG
{
    public static void dfs(Node root, int level, int index, Dictionary<int, int> mp)
    {
        if (root == null)
            return;

        // correct diagonal key = level - index
        if (mp.ContainsKey(level - index))
            mp[level - index] += root.data;
        else
            mp[level - index] = root.data;

        // left → next diagonal
        dfs(root.left, level + 1, index - 1, mp);

        // right → same diagonal direction
        dfs(root.right, level + 1, index + 1, mp);
    }

    public static List<int> diagonalSum(Node root)
    {
        Dictionary<int, int> mp = new Dictionary<int, int>();
        dfs(root, 0, 0, mp);

        List<int> ans = new List<int>();
        foreach (var it in mp)
        {
            ans.Add(it.Value);
        }
        return ans;
    }

    public static void Main()
    {
        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);

        root.left.left = new Node(3);
        root.left.right = new Node(5);

        root.right.left = new Node(2);

        List<int> ans = diagonalSum(root);

        Console.Write("Diagonal sum in a binary tree is: ");

        for (int i = 0; i < ans.Count; i++)
        {
            Console.Write(ans[i] + " ");
        }
    }
}
JavaScript
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function dfs(root, level, index, mp) {
    if (!root) return;

    // correct diagonal key = level - index
    if (mp.has(level - index)) {
        mp.set(level - index, mp.get(level - index) + root.data);
    } else {
        mp.set(level - index, root.data);
    }

    // left → next diagonal
    dfs(root.left, level + 1, index - 1, mp);

    // right → same diagonal direction
    dfs(root.right, level + 1, index + 1, mp);
}

function diagonalSum(root) {
    let mp = new Map();
    dfs(root, 0, 0, mp);

    let ans = [];
    for (let [key, value] of mp) {
        ans.push(value);
    }
    return ans;
}

// Driver code
let root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);

root.left.left = new Node(3);
root.left.right = new Node(5);

root.right.left = new Node(2);

let ans = diagonalSum(root);

console.log('Diagonal sum in a binary tree is:');
console.log(ans.join(' '));

Output
Diagonal sum in a binary tree is: 12 15 3 

Time Complexity-  O(n log n)
Space Complexity: O(n)

Using Diagonal Traversal (Map Based) - O(n log n) Time O(n) Space

The idea is to group nodes on the same diagonal and compute their sum. Assign a diagonal level (vd) starting from root as 0. For each node, add its value to map[vd]. Moving to the left child increases the diagonal (vd + 1), while moving to the right child keeps it the same. A map is used to store sums in sorted order of diagonals.

Algorithm:

  • Initialize a map to store (diagonal -> sum)
  • Traverse the tree using recursion
  • Update sum for each diagonal
  • Extract values from map into result vector
C++
// C++ Program to find diagonal sum in a Binary Tree
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;
    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

void solve(Node *root, int vd, map<int, int> &mp)
{
    if (!root)
        return;

    mp[vd] += root->data;

    // left child -> vd + 1
    solve(root->left, vd + 1, mp);

    // right child -> same vd
    solve(root->right, vd, mp);
}

vector<int> diagonalSum(Node *root)
{

    map<int, int> mp;

    solve(root, 0, mp);

    vector<int> res;

    for (auto it : mp)
        res.push_back(it.second);

    return res;
}


// Driver code
int main() {

    Node* root = new Node(10);
    root->left = new Node(8);
    root->right = new Node(2);
    
    root->left->left = new Node(3);
    root->left->right = new Node(5);
    
    root->right->left = new Node(2);

    vector<int> ans = diagonalSum(root);
    
    cout << "Diagonal sum in a binary tree is: ";

    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

struct Node* createNode(int val) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = val;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

void solve(struct Node* root, int vd, int** mp, int* mpSize) {
    if (!root)
        return;

    (*mp)[vd] += root->data;

    // left child -> vd + 1
    solve(root->left, vd + 1, mp, mpSize);

    // right child -> same vd
    solve(root->right, vd, mp, mpSize);
}

int* diagonalSum(struct Node* root, int* returnSize) {
    int mpSize = 1000; // assuming max size for simplicity
    int* mp = (int*)calloc(mpSize, sizeof(int));

    solve(root, 0, &mp, &mpSize);

    int resSize = 0;
    for (int i = 0; i < mpSize; i++) {
        if (mp[i]!= 0)
            resSize++;
    }

    int* res = (int*)malloc(resSize * sizeof(int));
    int index = 0;
    for (int i = 0; i < mpSize; i++) {
        if (mp[i]!= 0)
            res[index++] = mp[i];
    }

    *returnSize = resSize;
    return res;
}

int main() {
    struct Node* root = createNode(10);
    root->left = createNode(8);
    root->right = createNode(2);
    root->left->left = createNode(3);
    root->left->right = createNode(5);
    root->right->left = createNode(2);

    int returnSize;
    int* ans = diagonalSum(root, &returnSize);

    printf("Diagonal sum in a binary tree is: ");
    for (int i = 0; i < returnSize; i++) {
        printf("%d ", ans[i]);
    }
    printf("\n");

    free(ans);
    return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;

class Node {
    int data;
    Node left, right;

    public Node(int item) {
        data = item;
        left = right = null;
    }
}

public class GfG {
    void solve(Node root, int vd, Map<Integer, Integer> mp) {
        if (root == null)
            return;

        mp.put(vd, mp.getOrDefault(vd, 0) + root.data);

        // left child -> vd + 1
        solve(root.left, vd + 1, mp);

        // right child -> same vd
        solve(root.right, vd, mp);
    }

    ArrayList<Integer> diagonalSum(Node root) {
        Map<Integer, Integer> mp = new HashMap<>();

        solve(root, 0, mp);

        ArrayList<Integer> res = new ArrayList<>();

        for (Map.Entry<Integer, Integer> it : mp.entrySet())
            res.add(it.getValue());

        return res;
    }

    // Driver code
    public static void main(String[] args) {
        GfG tree = new GfG();

        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);

        ArrayList<Integer> ans = tree.diagonalSum(root); 

        System.out.println("Diagonal sum in a binary tree is: ");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i) + " ");
        }
    }
}
Python
from collections import defaultdict

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

def solve(root, vd, mp):
    if not root:
        return

    mp[vd] += root.data

    # left child -> vd + 1
    solve(root.left, vd + 1, mp)

    # right child -> same vd
    solve(root.right, vd, mp)

def diagonalSum(root):
    mp = defaultdict(int)

    solve(root, 0, mp)

    res = []

    for key in mp:
        res.append(mp[key])

    return res

# Driver code
if __name__ == '__main__':
    root = Node(10)
    root.left = Node(8)
    root.right = Node(2)
    root.left.left = Node(3)
    root.left.right = Node(5)
    root.right.left = Node(2)

    ans = diagonalSum(root)

    print('Diagonal sum in a binary tree is:', end=' ')
    for i in ans:
        print(i, end=' ')
C#
using System;
using System.Collections.Generic;

public class Node
{
    public int data;
    public Node left;
    public Node right;
    public Node(int val)
    {
        data = val;
        left = null;
        right = null;
    }
}

public class GfG
{
    public void Solve(Node root, int vd, Dictionary<int, int> mp)
    {
        if (root == null)
            return;

        if (!mp.ContainsKey(vd))
            mp[vd] = 0;

        mp[vd] += root.data;

        // left child -> vd + 1
        Solve(root.left, vd + 1, mp);

        // right child -> same vd
        Solve(root.right, vd, mp);
    }

    public List<int> DiagonalSumMethod(Node root)
    {
        Dictionary<int, int> mp = new Dictionary<int, int>();

        Solve(root, 0, mp);

        List<int> res = new List<int>();

        foreach (var it in mp)
            res.Add(it.Value);

        return res;
    }

    public static void Main(string[] args)
    {
        GfG ds = new GfG();  

        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);

        List<int> ans = ds.DiagonalSumMethod(root);

        Console.WriteLine("Diagonal sum in a binary tree is: ");

        foreach (int i in ans)
            Console.Write(i + " ");
    }
}
JavaScript
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function solve(root, vd, mp) {
    if (!root) return;

    if (!mp.has(vd)) mp.set(vd, 0);
    mp.set(vd, mp.get(vd) + root.data);

    // left child -> vd + 1
    solve(root.left, vd + 1, mp);

    // right child -> same vd
    solve(root.right, vd, mp);
}

function diagonalSum(root) {
    let mp = new Map();
    solve(root, 0, mp);
    let res = [];
    for (let [key, value] of mp) {
        res.push(value);
    }
    return res;
}

// Driver code
let root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);

let ans = diagonalSum(root);
console.log('Diagonal sum in a binary tree is:'); 
for (let i = 0; i < ans.length; i++) {
    console.log(ans[i] + ' ');
}

Output
Diagonal sum in a binary tree is: 12 15 3 

Time Complexity: O(n log n)
Space Complexity: O(n)

Iterative Level-Wise Diagonal Traversal Using a Queue - O(n) Time O(n) Space

The idea is to use a queue to store left children for future processing. The traversal always moves right first, accumulating the sum for the current diagonal. When the right chain ends, the next node is taken from the queue to begin a new diagonal, and this process continues until all nodes are covered.

Let us understand with an example:

Start: grid (list) = {}
Step-by-step traversal:

  • Node 10 -> sum = 10 -> left (8 pushed), move right -> 2 -> grid = {0: 12}
  • Node 2 -> sum = 12 -> left (2 pushed), move right -> NULL
  • Move to next diagonal -> Node 8 -> grid = {0: 12, 2: 8}
  • Node 8 -> sum = 8 -> left (3 pushed), move right -> 5 -> grid = {0: 12, 2: 13}
  • Node 5 -> sum = 13 -> move right -> NULL
  • Move to next -> Node 2 -> grid = {0: 12, 2: 15}
  • Node 2 -> sum = 15 -> move right -> NULL
  • Move to next -> Node 3 -> grid = {0: 12, 2: 15, 4: 3}

Final grid: 0 -> 12, 2 -> 15, 4 -> 3, Output: 12 15 3

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left, *right;

    Node(int val)
    {
        data = val;
        left = right = nullptr;
    }
};

// function for diagonal using queue
vector<int> diagonalSum(Node *root)
{
    vector<int> ans;
    if (!root)
        return ans;

    queue<Node *> q;
    q.push(root);

    while (!q.empty())
    {

        int size = q.size();
        int sum = 0;

        // process current diagonal
        for (int i = 0; i < size; i++)
        {

            Node *curr = q.front();
            q.pop();

            // traverse entire right chain
            while (curr)
            {
                sum += curr->data;

                if (curr->left)
                    q.push(curr->left);

                curr = curr->right;
            }
        }

        ans.push_back(sum);
    }

    return ans;
}

// Driver code
int main()
{

    Node *root = new Node(10);
    root->left = new Node(8);
    root->right = new Node(2);

    root->left->left = new Node(3);
    root->left->right = new Node(5);

    root->right->left = new Node(2);

    vector<int> ans = diagonalSum(root);

    cout << "Diagonal sum in a binary tree is: ";

    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i] << " ";
    }

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.ArrayList;


class Node {
  public int data;
  Node left, right;


  Node(int val) {
    data = val;
    left = right = null;
  }
}

public class GfG {
  // function for diagonal using queue
  static ArrayList<Integer> diagonalSum(Node root) {
    ArrayList<Integer> ans = new ArrayList<>();
    if (root == null)
      return ans;

    Queue<Node> q = new LinkedList<>();
    q.add(root);

    while (!q.isEmpty()) {

      int size = q.size();
      int sum = 0;

      // process current diagonal
      for (int i = 0; i < size; i++) {

        Node curr = q.poll();

        // traverse entire right chain
        while (curr!= null) {
          sum += curr.data;

          if (curr.left!= null)
            q.add(curr.left);

          curr = curr.right;
        }
      }

      ans.add(sum);
    }

    return ans;
  }

  public static void main(String[] args) {
    Node root = new Node(10);
    root.left = new Node(8);
    root.right = new Node(2);

    root.left.left = new Node(3);
    root.left.right = new Node(5);

    root.right.left = new Node(2);

    ArrayList<Integer> ans = diagonalSum(root);

    System.out.print("Diagonal sum in a binary tree is: ");
    for (int i = 0; i < ans.size(); i++) {
      System.out.print(ans.get(i) + " ");
    }
  }
}
Python
from collections import deque


class Node:
  def __init__(self, val):
    self.data = val
    self.left = None
    self.right = None

# function for diagonal using queue
def diagonalSum(root):
  ans = []
  if not root:
    return ans

  q = deque([root])

  while q:

    size = len(q)
    sum = 0

    # process current diagonal
    for i in range(size):

      curr = q.popleft()

      # traverse entire right chain
      while curr:
        sum += curr.data

        if curr.left:
          q.append(curr.left)

        curr = curr.right

    ans.append(sum)

  return ans

# Driver code
if __name__ == '__main__':
  root = Node(10)
  root.left = Node(8)
  root.right = Node(2)

  root.left.left = Node(3)
  root.left.right = Node(5)

  root.right.left = Node(2)

  ans = diagonalSum(root)

  print('Diagonal sum in a binary tree is:', end=' ')
  for i in ans:
    print(i, end=' ')
C#
using System;
using System.Collections.Generic;


class Node
{
    public int data;
    public Node left, right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GfG
{

    // function for diagonal using queue
    public List<int> diagonalSum(Node root)
    {

        List<int> ans = new List<int>();
        if (root == null)
            return ans;

        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0)
        {

            int size = q.Count;
            int sum = 0;

            // process current diagonal
            for (int i = 0; i < size; i++)
            {

                Node curr = q.Dequeue();

                // traverse entire right chain
                while (curr != null)
                {
                    sum += curr.data;

                    if (curr.left != null)
                        q.Enqueue(curr.left);

                    curr = curr.right;
                }
            }

            ans.Add(sum);
        }

        return ans;
    }

    public static void Main(string[] args)
    {

        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);

        root.left.left = new Node(3);
        root.left.right = new Node(5);

        root.right.left = new Node(2);

        GfG obj = new GfG();   
        List<int> ans = obj.diagonalSum(root);  

        Console.WriteLine("Diagonal sum in a binary tree is: ");

        for (int i = 0; i < ans.Count; i++)
        {
            Console.Write(ans[i] + " ");
        }
    }
}
JavaScript
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// function for diagonal using queue
function diagonalSum(root) {

    let ans = [];
    if (!root) return ans;

    let q = [];
    q.push(root);

    while (q.length > 0) {

        let size = q.length;
        let sum = 0;

        // process current diagonal
        for (let i = 0; i < size; i++) {

            let curr = q.shift();

            // traverse entire right chain
            while (curr) {
                sum += curr.data;

                if (curr.left)
                    q.push(curr.left);

                curr = curr.right;
            }
        }

        ans.push(sum);
    }

    return ans;
}

// driver code
(function () {

    let root = new Node(10);
    root.left = new Node(8);
    root.right = new Node(2);

    root.left.left = new Node(3);
    root.left.right = new Node(5);

    root.right.left = new Node(2);

    let ans = diagonalSum(root);

    console.log("Diagonal sum in a binary tree is: ");

    for (let i = 0; i < ans.length; i++) {
        console.log(ans[i] + " ");
    }

})();

Output
Diagonal sum in a binary tree is: 12 15 3 

Time Complexity: O(n)
Space Complexity: O(n)

Comment