First you should find the positions, you can do this by counting number of left and rights spend to reach specific node:
1 : l = 0, r = 0
/ \
/ \
l=1,r=0 2 3 : l = 0, r = 1.
/ \ / \
... 4...5 6...7 ....
Simply you can traverse your binary tree and finally calculate LorR = NumberOfLeft - NumberOfRights
for each node, then group this numbers (by their LorR
value) together and find each groups sum (print them from most positive to most negative value of LorR
).
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:
1
/ \
/ \
/ \
2 3 upto this we used 1/2 size of pyramid
/ \ / \
/ \ / \
4 5 6 7 upto this we used 1/2 + 1/4 part of pyramid
/ \ / \ / \ / \
5 9 1 3 6 7 5 5 upto this we used 1/2 + 1/4 + 1/4 part of pyramid
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.