-1

I have a function that returns the first node of a tree,

node* primeiro(tree r){
    while(r->left != NULL){
        r = r->left;
    }
    return r;
}

BTW, the percuss is made in order. So the function returns the leftmost leaf of the tree and the function presumes that the tree is not empty. How can I implement this in a recursive way?

 node* primeiro (tree r) {
    while (r->left != NULL) {
     r = primeiro (r->left); 
    }
    return r;
}

This is not working.

Caleb Kleveter
  • 11,170
  • 8
  • 62
  • 92
Rafael Camara
  • 33
  • 1
  • 6

4 Answers4

2

The problem is in using while. You need simple recursion termination condition.

node* primeiro (tree r) {
    if (r->left != NULL) {
        r = primeiro (r->left); 
    }
    return r;
}
kocica
  • 6,412
  • 2
  • 14
  • 35
0

Instead of using condition r->left != NULL for while loop, check it for true or false. (that will be base condition for the termination of recursion).

0

When we speak of "recursive functions", we usually mean "functions that use recursion to loop"...

Both of your functions are using while to loop. You should focus on transforming that while loop into a recursive function call.

Consider this loop:

int fubar(int x) {
    while (x > 0) {
        x--;
    }
    return x;
}

It transforms into this:

int fubar(int x) {
    if (x > 0) {
        return fubar(x - 1);
    }
    return x;
}

Notice how similar the two are. The differences are:

  • You're changing x not directly but by passing a different value of x in
  • Your loop test is in an if statement, not while...
  • Again, you're not looping using while; instead you should be calling fubar again, passing in a new value and returning its result.

Important note: There could be significant benefits to ensuring every recursive function call is followed immediately by a return (without any intermediate calculations required).

autistic
  • 1
  • 3
  • 35
  • 80
0

When iteration is being replaced with recursion, it may be easier to derive the right code by beginning with the infinite recursive loop:

node* primeiro(tree r){
    /* What goes in the recursive loop body? */
    return primeiro(r);
}

You can now ask under what would the next value of the iteration, and when does the loop stop. The next value is pretty straight forward.

node* primeiro(tree r){
    /* When does the recursive loop stop? */
    r = r->left;
    return primeiro(r);
}

From the while loop logic, the loop stops when r->left is NULL. At that point, you would return r.

node* primeiro(tree r){
    if (r->left == NULL) return r;
    r = r->left;
    return primeiro(r);
}
jxh
  • 69,070
  • 8
  • 110
  • 193