level of binary tree

Oct 29, 2015 at 8:29am
Hello,

I tried to do find the max value at certain level of the binary tree (say the third level), but I have no idea how to do it. I try to implement counter but as the function is recursive it will always reset the value to 0 again. here is my sample code.

if(p == NULL)
{
return 0;
}

int max = p->value;

if(p->left != NULL)
{
int leftmax = search(p->left);
if(max < leftmax)
{
max = leftmax;
}
}

if(p->right != NULL)
{
int rightmax = search(p->right);
if(max < rightmax)
{
max = rightmax;
}
}

return max;
Last edited on Oct 29, 2015 at 8:59am
Oct 29, 2015 at 8:46am
It would help if you posted that code in a function as it'll probably be a recursive function.

Are you familiar with recursion?
Oct 29, 2015 at 9:03am
ok, it definitely a recursive. sorry i forgot to include the function signature.

int search(Node* p)
{

if(p == NULL)
{
return 0;
}

int max = p->value;

if(p->left != NULL)
{
int leftmax = search(p->left);
if(max < leftmax)
{
max = leftmax;
}
}

if(p->right != NULL)
{
int rightmax = search(p->right);
if(max < rightmax)
{
max = rightmax;
}
}

return max;
}

im not really familiar with recursion, but i had used it before. The problem is i want to put counter in it but if i initialise "int count = 0" for example, it will keep on re-initialise count as the function is recursive.
Oct 29, 2015 at 7:46pm
You also forgot to format your code. It kinda hard to talk about it when we can't read it.

If we called it depth instead of search and have it return the depth as an unsigned number, it might look like this.

So it can work like this:
if the node is null, the return 0
left_depth is the depth of the left node
right_depth is the depth of the right node
return 1 + max(left_depth, right_depth)

Does that algorithm seem ok? If it does, do you think you can code it?
Topic archived. No new replies allowed.