Google Interview Question

Q. Write a function that takes two trees as an argument and returns true if they are equal.

Interview Answers

Anonymous

Dec 4, 2015

Traversal list won't work from comparing one traversal alone. It is possible for different trees to produce the same list in a tree order traversal. Even if it did work producing a list would be unnecessary. Boolean isEqual(t1, t2){ If( both null){ Return true; } if (t1.val != t2.val){ Return false; } Return isEqual(t1.left,t2.left) && isEqual(t1.right,t2.right); }

Anonymous

Nov 18, 2015

boolean compare(TreeSet ts1, TreeSet ts2){ return ts1.equals(ts2); }

Anonymous

Nov 26, 2015

Do a simple preorder DFS traversal on the 2 trees and then simply compare the nodes in the 2 traversal lists. Overall it is an O(n) operation in terms of time complexity.