New update is available. Click here to update.

Problem title
Difficulty
Avg time to solve

SQL Practice
Easy
--
Running Median
Hard
46 mins
Rotting Oranges
Moderate
20 mins
Reverse Level Order Traversal
Moderate
30 mins
Subtree of Another Tree
Easy
10 mins
Compare Version Numbers
Easy
10 mins
Circularly Linked
Easy
15 mins
Print Reverse LinkedList
Easy
15 mins
Sorted Matrix
Moderate
25 mins
Diagonal Sum
Easy
23 mins

Diagonal Sum

Contributed by
Ashwani
Easy
Avg time to solve 23 mins
Success Rate 75 %
Share
26 upvotes

Problem Statement

Given a Binary Tree of 'N' nodes, find and print a list containing the sums of all the diagonals. When calculating the sum of each diagonal, consider the diagonals from right to left.

Diagonals of the binary tree are :

alt-text

There are three diagonals :

Diagonal 1 : 8 10 14

Diagonal 2 : 3 6 7 13

Diagonal 3 : 1 4

Example :

For the given binary tree : 

alt-text

Output : 24 14 2

Explanation: Rightmost diagonal contains elements {5, 10 , 9} its sum is 24, middle diagonal contains elements {6, 3, 5} its sum is 14, leftmost diagonal contains elements {2}. Thus the answer should be “24 14 2”.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1 :
1 2 3 -1 4 4 -1 -1 5 6 -1 -1 -1 -1 -1
Sample Output 1:
4 15 6
Explanation For Sample Input 1 :
The input binary tree will be represented as 

alt-text

From the above representation, the rightmost diagonal contains elements {1, 3}, the middle diagonal contains elements {2, 4, 4, 5} and leftmost diagonal elements are {6}. Thus the list should contain “4 15 6”.
Sample Input 2:
1 2 3 -1 -1 -1 -1
Sample Output 2 :
4 2
Reset Code
Full screen
copy-code
Console