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.
- Diagonal Traversal of Binary Tree
- Kth node in Diagonal Traversal of Binary Tree
- Iterative diagonal traversal of binary tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Check whether a binary tree is a full binary tree or not
- Binary Tree to Binary Search Tree Conversion using STL set
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree | Set 1
- Check whether a given binary tree is skewed binary tree or not?
- Binary Tree to Binary Search Tree Conversion
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
Improved By : SHUBHAMSINGH10