I would like to test if two given BSTs (Binary Search Trees) are equal in Java. The BST nodes do not have pointers to the parent nodes.
The simplest solution is to traverse both BSTs, create two traversal lists and test if the lists are equal. However it requires O(N) memory.
I would like to try another way: create an Iterator, which traverses the BSTs, and … the rest is obvious.
Does it make sense? Is there any “better” (simpler and efficient) solution to test if two BSTs are equal?
Implement a recursive
equals()method. It would require no memory, and would be easy to code.Something like this should work:
Note that you should override
hashCode()to reflect this implementation, so consider naming the above impl asequalsDeep()instead and skipping thehashCode()impl.