Consider lines of slope -1 passing between nodes (dotted lines in below diagram). Diagonal sum in a binary tree is sum of all node’s data lying between these lines. Given a Binary Tree, 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.
The idea is to keep track of vertical distance from top diagonal passing through root. We increment the vertical distance we go down to next diagonal.
1. Add root with vertical distance as 0 to the queue.
2. Process the sum of all right child and right of right child and so on.
3. Add left child current node into the queue for later processing. The vertical distance of left child is vertical distance of current node plus 1.
4. Keep doing 2nd, 3rd and 4th step till the queue is empty.
Following is the implementation of above idea.
Diagonal sum in a binary tree is - 9 19 42
This problem was for diagonals from top to bottom and slope -1. Try the same problem for slope +1.
This article is contributed by Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Diagonal Traversal of Binary Tree
- Iterative diagonal traversal of binary tree
- Kth node in Diagonal Traversal of Binary Tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Minimum swap required to convert binary tree to binary search tree
- Binary Tree | Set 3 (Types of Binary Tree)
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Binary Tree to Binary Search Tree Conversion using STL set
- Check whether a given binary tree is skewed binary tree or not?
- Difference between Binary Tree and Binary Search Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
Improved By : SHUBHAMSINGH10