Web Toolbar by Wibiya

Pages

Friday, January 20, 2012

Given a Binary Search Tree, print nodes within a given range.

Solution #1:

Algorithm:
- If the current node lies between 'min' and 'max', print it.
- If the current node is greater than 'min', recursively call left child.
- If the current node is lesser than 'max', recursively call right child.

Here is the code,

void printRange(struct node* root, int min, int max)
{
    if(root == NULL)
        return;
    
    if( (min <= root->data) && (root->data <= max) )
        printf("%d\n", root->data);

    if(min < root->data)
        printRange(root->left, min, max);

    if(root->data < max)
        printRange(root->right, min, max);
}

No comments: