Hash for tree structure
Find the center of the tree. Then run the recursive algorithm as such from the center:
recurse(u, p):
hash = INITH
vector childrenhash = {}
for each (u,v) in G:
if v!=p:
childrenhash.insert(recurse(v,u))
childrenhash.sort()
for elem in childrenhash:
hash = (hash * (elem xor PR)) % MOD
return hash
Select appropriate values ββfor INITH
, MOD
and PR
.
Two isomorphic trees will share the same hash.
source to share
If you throw away the node labels, the rest is the number of children for each node. This way you can just count the number of children for each node and write them all in one line (array, vector, ...).
Example:
a 2
/ \ / \
b c => 0 2 => 2,0,2,0,0
/ \ / \
d e 0 0
Now, suppose you say the following trees are to be considered equal:
a a
/ | \ / | \
b c d b c d
/ \ \ / \ |
d e f d e f
You can add another transformation step to the same idea: sort the children:
a 3 3
/ | \ / | \ / | \
b c d => 0 2 1 => 0 1 2 => 3,0,1,2,0,0,0
/ \ \ / \ \ | / \
d e f 0 0 0 0 0 0
a 3 3
/ | \ / | \ / | \
b c d => 2 0 1 => 0 1 2 => 3,0,1,2,0,0,0
/ \ | / \ | | / \
d e f 0 0 0 0 0 0
I'll probably follow the idea in @gilleain's link: https://math.stackexchange.com/questions/1604260/algorithm-for-equality-of-trees-of-restricted-depth
source to share