Meta Interview Question

Given two binary trees, return true if they have same elements (irrespective of tree structure)

Interview Answers

Anonymous

Feb 11, 2011

traverse 1st tree and add all node data into hash table of traverse 2nd tree and foreach node: if data not in hashtable return false; otherwise, decrease count by 1, remove the key if count is 0 return hashtable.ItemCount == 0;

3

Anonymous

Sep 24, 2010

add all elements of one tree to a hashtable for the other tree, add them to the same hashtable and if it's empty, return false, and if there is a collision, erase the entry from the table if nothing's left in the table after, we're good

2

Anonymous

Dec 5, 2011

If the trees are binary search trees, it is possible to compare them quickly by calling repeatedly getSuccessor();

Anonymous

Nov 22, 2010

The above algorithm is totally wrong. Let's take a look at this counter example: Tree A: 1 2 2 Tree B: 1 1 2 Your algorithm will return "we are good" in this case.

Anonymous

Dec 16, 2010

traverse each tree into an array, sort them, compare