Amazon Interview Question

Design and implement an algorithm to determine if a binary tree is symmetric.

Interview Answers

Anonymous

Apr 12, 2010

Each node in a binary tree can be mapped to a binary string encoding its position in the tree. For each level below the root, the string should consist of a 0 if the node requires a left traversal or 1 if a right. This is important because a bit string s and its inverse ~s will represent symmetric paths down the tree. A solution to this symmetry problem would perform a tree traversal and, at each node in the traversal, encode the path as described above. Then, negate the path to generate ~path and fetch that node. If it exists and is identical to the original node, continue the traversal - otherwise, we stop (not symmetric).

Anonymous

Aug 27, 2011

@wiiam Wu Pure Trash.

Anonymous

Feb 14, 2011

symmetric(t) = reversed(t.left,t.right) mirrored (t1,t2) = mirrored(t1.left, t2.right) && t1.data=t2.data && mirrored(t1.right, t2.left) inspired from : http://stackoverflow.com/questions/1482822/how-can-we-find-given-two-binary-trees-that-they-are-equal gro.eeei@jzw (reversed)