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.
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.
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.
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:
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
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}