Web Toolbar by Wibiya

Pages

Thursday, January 12, 2012

Trim a tree so that all the elements in the tree are between min and max.

Solution #1: If the root is lesses than the 'min' then we know that we can trim the root as well as the entire left sub-tree. Similarly, if the root is greater than the 'max' then we know that we can trim the root as well as the entire right sub-tree. Here is the recursive code,

void freeTree(struct node* root)
{
    if(root == NULL)
        return;

    freeTree(root->left);
    freeTree(root->right);
    free(root);
}

struct node* trim(struct node* root, int min, int max)
{
    if(root == NULL)
        return NULL;

    if(root->data < min)
    {
        struct node* temp = root->right;
        freeTree(root->left);
        free(root);
        return trim(temp, min, max);
    }
    else if(root->data > max)
    {
        struct node* temp = root->left;
        freeTree(root->right);
        free(root);
        return trim(temp, min, max);
    }

    root->left = trim(root->left, min, max);
    root->right = trim(root->right, min, max);

    return root;
}

int main()
{
    struct node *root;

    insert(&root, 100);
    insert(&root, 50);
    insert(&root, 25);
    insert(&root, 40);
    insert(&root, 30);
    insert(&root, 35);
    insert(&root, 120);
    insert(&root, 110);
    insert(&root, 32);

    Inorder(root);
    printf("\n");

    root = trim(root, 30, 50);

    Inorder(root);
    printf("\n");

    return 0;
}

No comments: