Created
November 8, 2017 16:29
-
-
Save milovtim/30c5fd4cd612a9fd118cd9f109b05ca1 to your computer and use it in GitHub Desktop.
Example of guava TreeTraversal. Iterations:
breadthFirst, depthFirst (pre-order, post-order)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.collect.TreeTraverser | |
// format (id/parentId) | |
def data = [ | |
'1/0', | |
'2/1', '3/1', | |
'4/2', '5/2', '6/3', | |
'7/5', '8/5', '9/6' | |
] | |
def tree = TreeTraverser.using({ | |
parent -> | |
data.findAll { | |
child -> parent.split('/')[0] == child.split('/')[1] | |
} | |
}) | |
def printClosure = { | |
println "${' ' * delegate.i++}$it" | |
} | |
i = 0 | |
tree.breadthFirstTraversal('1').each(printClosure).last() | |
/* | |
1 | |
2/1 | |
3/1 | |
4/2 | |
5/2 | |
6/3 | |
7/5 | |
8/5 | |
9/6 | |
*/ | |
i = 0 //reset closure delegate var | |
tree.preOrderTraversal('1').each(printClosure) | |
/* | |
1 | |
2/1 | |
4/2 | |
5/2 | |
7/5 | |
8/5 | |
3/1 | |
6/3 | |
9/6 | |
*/ | |
i = 0 | |
tree.postOrderTraversal('1').each(printClosure) | |
/* | |
4/2 | |
7/5 | |
8/5 | |
5/2 | |
2/1 | |
9/6 | |
6/3 | |
3/1 | |
1 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment