May 3, 2013

Mirror a Binary Tree


Question: Given a binary tree, write a program to mirror the tree (i.e. swap left and right nodes of the original tree).

Time Complexity: O(n)


tree *
tree_mirror(tree *t) 
{
    tree *tmp = NULL;

    if (!t) {
        return NULL;
    }

    tmp = (tree *) malloc (sizeof(tree));
    if (!tmp) {
        exit(ENOMEM);
    }

    tmp->data = t->data;
    tmp->right = tree_mirror(t->left);
    tmp->left = tree_mirror(t->right);

    return (tmp);
}

Duplicate a Binary Tree

Question: Given a binary tree, write a program to duplicate the tree (i.e. create an exact copy of the tree).

Time Complexity: O(n)

tree *
tree_duplicate(tree *t) 
{
    tree *tmp = NULL;

    if (!t) {
        return NULL;
    }

    tmp = (tree *) malloc (sizeof(tree));
    if (!tmp) {
        exit(ENOMEM);
    }

    tmp->data = t->data;
    tmp->left = tree_duplicate(t->left);
    tmp->right = tree_duplicate(t->right);

    return (tmp);
}