I´d like to simplify a network of lines by merging small segments into interconnected compartements.
The algorithm should merge the lines based on the smallest cost (degree) at the junction points to the adjacent lines and terminated for a segment when a certain "degree" threshold is reached (See picture). Or in technichal terms:
Select a random line from table where start OR endpoint are not connected to other geometries and assign a unique id.
Generate a path choosing the least cost (best alignment of intersecting/touching lines) at intersections, until defined alignment threshold is reached, then assign created id from 1. to whole path.
Repeat this for remaining segments until all lines have been numbered.
This should be done for the whole dataset and all line vectors included.

As an example, there is one plugin describing the process I want in QGis 2.18 called MergeLines, wich simplifies the network structure by alignement but there is no possibility to specify a custom paramter (maximum alignment offset) to define the end of a line segment.
Are there ready tools for that task, preferably using open source solutions like PostGIS/pgRouting? (Something like undirected routing based on alignment as cost?)