How to find the vertical sum of a binary tree.
For example,
Consider the binary tree below,
1
/ \
/ \
/ \
2 3
/ \ / \
/ \ / \
4 5 6 7
/ \ / \ / \ / \
5 9 1 3 6 7 5 5
For the above tree, Vertical sum should be calculated as follows,
- Line 1: 5
- Line 2: 4
- Line 3: 2,9,1
- Line 4: 5
- Line 5: 1,3,6
- Line 6: 6
- Line 7: 3,7,5
- Line 8: 7
- Line 9: 5
Output should be:
5,4,12,5,10,6,15,7,5
First you should find the positions, you can do this by counting number of left and rights spend to reach specific node:
Simply you can traverse your binary tree and finally calculate
LorR = NumberOfLeft - NumberOfRightsfor each node, then group this numbers (by theirLorRvalue) together and find each groups sum (print them from most positive to most negative value ofLorR).Update: This doesn’t answers for tree of height more than two, we can fix this problem with little modification in algorithm.
We can see tree as pyramid, each vertex of pyramid has length 1, after each branch remaining part of branch is equal to what passed in latest move, we show this in picture for tree of height 3:
This means in each step we calculate left values by their height (in fact each time multiply of 1/2 will be added to left value, except last time, which is equal to h-1 st value).
So for this case we have: 1 in root is in group 0, 3 in leaf is in group -1/2 + 1/4 + 1/4 = 0, 6 in leaf is in group 1/2 – 1/4 – 1/4 = 0
1 in leaf is in -1/2 + 1/4 – 1/4 = -1/2 and so on.
For preventing from rounding of 1/(2^x) to zero or other problems we can multiply our factors (1/2, 1/4, 1/8,…) to 2h-1. In fact in the first case I wrote we can say factors are multiplied by 22-1.