Created
March 13, 2019 18:22
-
-
Save igorlukanin/97b13a4c88806287195ee719202d1c7c to your computer and use it in GitHub Desktop.
findEqualSubtrees for fellaru
This file contains hidden or 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
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