[try Beta version]
Not logged in

 
Recursion and counting/incrementing

Jun 5, 2013 at 9:32pm
Hey

I'm practicing with recursion. I'm trying to write a function that will count all the nodes in a binary tree. given the following class definition.

1
2
3
4
5
  class Binode
{public:
    int n;
    Binode* l, *r;
}


So what I've come with is

1
2
3
4
5
6
7
8
9
int number(Binode* p, int& x)
{ if (p == NULL)
     return x;
  else
     {
      n++;
       return (number (p -> l, x)+ number (p -> r, x));
     }
}


Is there anyway to intialise x at the beggining? Also can anyone think of way to do this without having x as a parameter? So just a Binode* as a paramater?
Jun 5, 2013 at 9:38pm
You could use a static variable:

static int x = #;


Better answers below.
Last edited on Jun 5, 2013 at 9:48pm
Jun 5, 2013 at 9:38pm
Untested:

1
2
3
4
5
6
7
unsigned count_nodes(Binode*p)
{
    if ( p == nullptr )
         return 0 ;

    return 1 + count_nodes(p->l) + count_nodes(p->r) ;
}
Jun 5, 2013 at 9:40pm
1
2
3
4
size_t number( Binode* p )
{ 
   return ( p ? 1 + number( p->l ) + number( p->r ) : 0 );
}
Jun 5, 2013 at 9:45pm
In not quite real code:

1
2
3
4
5
int count(node* n)
{
    if(n == null) return 0;
    return count(n.leftChild) + count(n.rightChild) + 1;
}
Jun 5, 2013 at 9:55pm
That would work. Why didn't I think of that...

Thanks.

I' trying this one now which counts the depth of a tree. This is untested but I think it should work. Is their anyway you could do this with one parameter a Binode*?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int depth (Binode*p, int&x, int& y)
{  
      if ( p == NULL)
        {  
                if(x > y)
                  {
                        y =  x;
                        x = 0;                        
                        return y;
                  }
      else
         {x++;
           return depth(p-> l, x, y) > depth(p -> r, x, y) ? return depth(p-> l, x, y) : depth(p -> r, x, y);
         }
}


I I know this is inefficient as well...
Last edited on Jun 5, 2013 at 9:57pm
Jun 5, 2013 at 10:04pm
1
2
3
4
5
6
7
8
9
10
unsigned depth(Binode* p)
{
    if  ( p == nullptr )
        return 0 ;

    unsigned rdepth = depth(p->r);
    unsigned ldepth = depth(p->l) ;

    return rdepth < ldepth ? 1+ldepth : 1+rdepth ;
}


[edit: corrected bug]
Last edited on Jun 5, 2013 at 10:33pm
Jun 5, 2013 at 10:17pm
EDIT: I'm sure it works just trying to figure out how. lol. Its the last comparison thats baffling me.
Last edited on Jun 5, 2013 at 10:29pm
Jun 5, 2013 at 11:29pm
Nothing is stopping you from playing around with the code or running it in a debugger to trace through it.

Maybe this will help you visualize what's going on:
http://ideone.com/4vI4e4
Jun 5, 2013 at 11:32pm
I can see whats going on but piecing the actual logic together is another issue. Got it now. The power of sleep.. Thank you for the help.
Last edited on Jun 6, 2013 at 12:49pm
Topic archived. No new replies allowed.