Implementing hashCode for a BST

青春壹個敷衍的年華 提交于 2019-12-11 03:54:34

问题


In Java to compare two objections for equality, you must implement both the equals method and the hashCode method. I need to compare two BSTs for equality. How do I implement the hashCode method in such a case? Now, implementing the hashCode on the Node class is simple enough: imagine my data is int. But I cannot just add the values of the node to check if the trees are equal. So how do I do it? Has anyone done this successfully?

I am thinking of many different things that I can do, but I am not sure how scalable they would be. For example I could use level order and for each level multiply by a large prime number, but I can't be sure that this would work. So maybe someone who understands better can help me. Thanks.


回答1:


I cannot just add the values of the node to check if the trees are equal.

Sure you can. hashCodes do not have to be unique, and if two BSTs have the same contents, then summing the node contents will give you the same results in each case, which satisfies the hashCode contract. Remember -- return 0 is always a valid implementation of hashCode(); uniqueness is not required.

(Summing the hashCodes of the node contents is, in fact, how TreeSet.hashCode() is implemented.)

On the other hand, if you care about structure, you could do something simple like 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 get you a decent structure-respecting hash function, too.



来源:https://stackoverflow.com/questions/29949683/implementing-hashcode-for-a-bst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!