Skip to content

Instantly share code, notes, and snippets.

@milovtim
Created November 8, 2017 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milovtim/30c5fd4cd612a9fd118cd9f109b05ca1 to your computer and use it in GitHub Desktop.
Save milovtim/30c5fd4cd612a9fd118cd9f109b05ca1 to your computer and use it in GitHub Desktop.
Example of guava TreeTraversal. Iterations: breadthFirst, depthFirst (pre-order, post-order)
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