Search code examples
calgorithmbinary-search-treeinorder

Get smallest three numbers from binary tree in c


I use inorder function to print data in binary search tree from smallest to largest element. how i can print only first three smallest element?

void inorder(struct node *root)
{
    // Depth-first
    // Inorder (LDR) --> <left> <data> <right>

    if(root == NULL)
        return;

    indorder(root -> left_child);

    printf("%d ", root -> value);

    inorder(root -> right_child);
}

I want to add new argument for first n element

void inorder(struct node *root, int n)

Solution

  • Make your function return the new value of n, so that after a recursive call you can see whether n is still positive and the current node's value should be printed. If not, then you can exit the recursion tree, as there is nothing more to do:

    int inorder(node *root, int n) {
        if (root == NULL || n <= 0) // Nothing to print here.
            return n;
        n = inorder(root -> left_child, n);
        if (n <= 0) // All required prints have been done, so exit recursion tree
            return 0;
        printf("%d ", root -> value);
        // Previous print counts as 1, so pass one less to next call:
        return inorder(root -> right_child, n-1);
    }