java - Implementing hashCode for a BST -
in java compare 2 objections equality, must implement both equals method , hashcode method. need compare 2 bsts equality. how implement hashcode method in such case? now, implementing hashcode on node class simple enough: imagine data int. cannot add values of node check if trees equal. how do it? has done successfully?
i thinking of many different things can do, not sure how scalable be. example use level order , each level multiply large prime number, can't sure work. maybe understands better can me. thanks.
i cannot add values of node check if trees equal.
sure can. hashcodes not have unique, , if 2 bsts have same contents, summing node contents give same results in each case, satisfies hashcode contract. remember -- return 0 always valid implementation of hashcode(); uniqueness not required.
(summing hashcodes of node contents is, in fact, how treeset.hashcode() implemented.)
on other hand, if care structure, simple implementing node.hashcode() with
int h = contents.hashcode(); h = h * 31 + objects.hashcode(leftchild); h = h * 31 + objects.hashcode(rightchild); return h; ...and that'd decent structure-respecting hash function, too.
Comments
Post a Comment