Hierarchy rollup

Hello

I have two tables : A and B. Based on them I have created first hierarchy (my is that left one)

My aim is to get the right hierarchy which is based on the 'Rollup flag". This flag is taken into account during transformation of hierarchy (for the left hierarchy it has not been used) .
If Flag is 0 for a departement hierarchy is going to rollup to the higher level departement (this one with flag 1)
It can have multiple levels e.g first tree departement levels can be 0 then 4 level departement is 1 so then we rollup

Could you help me ?