Reputation: 17784
I have the following directed acyclic graph where edge directions are from top to bottom
A
|
B
/ \
C D
/ \ |
E F |
\ / |
G |
\ /
H
and I want to insert special split nodes where the nodes split and merge nodes where they merge again, i.e, I want the above graph structure to be transformed into the graph below
A
|
B
|
B-S
/ \
C D
| |
C-S |
/ \ |
E F |
\ / |
C-M |
| |
G |
\ /
B-M
|
H
How can I do the above transformation?
Upvotes: 0
Views: 175
Reputation: 23029
I will rewrite the picture as this, so its clear which M
and S
are related. I am also considering the tree to have maximum of two children, but it can easily be updated to more children in merging part.
A
|
B
|
B-S1
/ \
C D
| |
C-S2 |
/ \ |
E F |
\ / |
C-M2 |
| |
G |
\ /
B-M1
|
H
The main principle is that when you do the split, you have to carry through all the other nodes the information about that until you merge them again.
The alghoritm will be as following:
Start: Create stack
variable and push A
to it together with empty tokenStack
(it will be like one object {node: A, tokenStack: {}}
item
from stack
item.parents.length
item.token
exists
tokenStack
and save it inside item.token
tokenStack
. Take that value out of your tokenStack
and you can continue with 3.item.childrens.length
stack
together with unchanged tokenStack
tokenStack
, save it to current item.token
and push both children to stack
together with tokenStack
Now you did it all and Split and Merge nodes have the same item.token
note: You can also save information about all the existing tokens in tokenStack
during the flow if you want later investigate which nodes are in left/right part of which split branches.
Upvotes: 1