Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17784

Inserting nodes at split and merges of directed acyclic graphs

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

Answers (1)

libik
libik

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: {}}

  1. Take item from stack
  2. Check number of parents with item.parents.length
    • If it is 2, check if item.token exists
      • If not, take last item from tokenStack and save it inside item.token
        • Skip everything else below and continue from 1.
      • If there is value existing, it should be same as your last value in tokenStack. Take that value out of your tokenStack and you can continue with 3.
  3. Check number of children with item.childrens.length
    • If equal to 1, push that children to stack together with unchanged tokenStack
    • If there are two children, do the split, create token (i.e. unique string), add this token to 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

Related Questions