Say you have to traverse a tree or a graph in a reactive fashion, no problem! Project Reactor has got you covered. Suppose you have a Node object that looks like the following:
And Suppose you have the following tree:
In the snippet above node2 and node4 have a marked value equals to true. In the following examples I will show how you can search a marked node using breadth first and depth first recursions. Those are just two types of algorithms that are used for traversing a tree or a graph. With DFS, the recursion starts at the root node and explores each branch before moving to the adjacent nodes. With BFS the adjacent nodes are explored before the child nodes. You can find more info on those techniques here.
Breadth First Search is generally recommended for trees that are very tall but not too wide or when the wanted node is closer to the root node. With Reactor you can execute BFS with the method Flux.expand.
The bfsRecursion test shows how the whole tree is traversed when the expand method is used. The bfsFindFirstMarked method executes a breadth search of a marked node. In this instance the recursion stops when the node is found due to the use of takeUntil. Because this example is using BFS then node2 is found before node4.
Depth First Search is generally recommended for trees that are not too tall but wide or when the wanted node is further away from the root node. With Reactor you can execute DFS with the method Flux.expandDeep.
The dfsRecursion test shows how the tree is traversed in a depth first order compared to the previous example. The dfsFindFirstMarked method executes a depth search of a marked node, as a result node4 is found before node2.
The complete source code for the snippets illustrated in this article can be found in the java-series repo.