Amazon Interview Question

Code to check if a Binary tree is symmetrical.

Interview Answers

Anonymous

Sep 29, 2011

Try something like huffman coding. 0 for left, 1 for right. Traverse and check for palindrome :D

2

Anonymous

Jan 24, 2011

Or you could prepare a string representation of the in order transversal, a symmertrial BST will have a palindrom-ic string representation.

3

Anonymous

Nov 16, 2010

typedef struct _Tree { struct _Tree *left, *right; ... } Tree; int count_nodes(Tree *t) { if (t == NULL) return 0; return 1 + count_nodes(t->left) + count_nodes(t->right); } int is_symmetrical(Tree *t) { if (t == NULL) return 1; return is_symmetrical(t->left) && is_symmetrical(t->right) && count_nodes(t->left) == count_nodes(t->right); }

1