Given a binary tree, calculate the sum of all nodes for each diagonal having negative slope \. Assume that the left and right child of a node makes a 45–degree angle with the parent.

For example, consider the following binary tree having three diagonals. The sum of diagonals is 10, 15, and 11.
 

Diagonal Sum of Binary Tree

Practice this problem

We can easily solve this problem with the help of hashing. The idea is to create an empty map where each key in the map represents a diagonal in the binary tree, and its value maintains the sum of all nodes present in the diagonal. Then perform a preorder traversal on the tree and update the map. For each node, recur for its left subtree by increasing the diagonal by one and recur for the right subtree with the same diagonal.

This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

10 15 11

Java


Download  Run Code

Output:

[10, 15, 11]

Python


Download  Run Code

Output:

[10, 15, 11]

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.

 
Exercise:

1. Extend the solution to print nodes of every diagonal.

2. Modify the solution to print the diagonal sum for diagonals having a positive slope /.