Web Toolbar by Wibiya

Pages

Tuesday, January 10, 2012

Write a program to find if a tree is symmetric.

Solution #1: A symmetric binary tree is one where if you draw a vertical line passing through the root node then the left half should be the mirror image of the right half. Here is the recursive code,
int isSymmetric(struct node* l, struct node* r)
{
    if((l == NULL) && (r == NULL))
        return 1;

    if(((l == NULL) && (r != NULL)) || 
            ((l != NULL) && (r == NULL)))
        return 0;

    return isSymmetric(l->left, r->right) && isSymmetric(l->right, r->left);
}

1 comment:

Anonymous said...

I guess you need to add l->data == r->data &&.... in the return statement