Skip to content

Instantly share code, notes, and snippets.

@igorlukanin
Created March 13, 2019 18:22
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 igorlukanin/97b13a4c88806287195ee719202d1c7c to your computer and use it in GitHub Desktop.
Save igorlukanin/97b13a4c88806287195ee719202d1c7c to your computer and use it in GitHub Desktop.
findEqualSubtrees for fellaru
data class TreeNode(
val value: Char,
val left: TreeNode? = null,
val right: TreeNode? = null
)
val tree = TreeNode(
'a',
TreeNode('b',
TreeNode('c'),
TreeNode('e')
),
TreeNode(
'b',
TreeNode('c'),
TreeNode('e')
)
)
fun Char.getHash() = 1 shl (this - 'a')
fun TreeNode.getHash(duplicates: MutableSet<TreeNode>, set: MutableSet<Int> = mutableSetOf()): Int {
// We need to find only one duplicate
if (duplicates.size > 0) {
return 0
}
val leftHash = left?.getHash(duplicates, set) ?: 0
val rightHash = right?.getHash(duplicates, set) ?: 0
val hash = value.getHash() or leftHash or rightHash
// A leaf is not a subtree!
if (leftHash == 0 && rightHash == 0) {
return hash
}
if (!set.add(hash)) {
duplicates.add(this)
}
return hash
}
fun TreeNode.findEqualSubtrees(): TreeNode? {
val duplicates = mutableSetOf<TreeNode>()
getHash(duplicates)
return duplicates.firstOrNull()
}
fun main(args: Array<String>) {
println(tree.findEqualSubtrees())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment