Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max function c tree height

Tags:

c

tree

max

is there a max function in c so i can do something like this to calculate tree height :or perhaps there is a better way to calculate tree height.

int height(struct node *tree)
{ 
    if (tree == NULL) return 0;
    return 1 + max(height (tree->left), height (tree->right)); 
}

if so what includes do i need?

currently i get this error :

dict-tree.o: In function 'height':
/home/ex10/dict-tree.c:36: undefined reference to `max'

like image 706
learner123 Avatar asked Aug 24 '26 17:08

learner123


2 Answers

No, there isn't one built in. Typically you'd write your own inline function, e.g.

static inline int max(int a, int b)
{
    return (a > b) ? a : b;
}

(using whichever 'inline' hint syntax your compiler prefers). In your case, though, you might as well just spell this out manually - it's simple enough:

int height(struct node *tree)
{ 
    int height_left, height_right;
    if (tree == NULL) return 0;

    height_left = height (tree->left);
    heigth_right = height (tree->right);

    return 1 + ((height_left > height_right) ? height_left : height_right);
}

N.B. beware of the max macro trap. It's tempting to do something like

#define MAX(a,b) (((a) > (b)) ? (a) : (b))

which you can then use for any inputs regardless of their types, but the problem here is if either of the input expressions have side effects, e.g. MAX(++i, ++j). The issue then is that the side effects will get evaluated twice for whichever of the inputs is the max. If you're going to code up max you must use an (inline) function rather than a macro. Unfortuantely since you're in C not C++ without overloading / templates this will limit you to one set of input / output types per named max function.

like image 59
Rup Avatar answered Aug 26 '26 10:08

Rup


Probably because max is an undefined function,

try implementing max first before proceeding.

int max(int a, int b) {
    if(a > b) return a;
    else return b;
}
like image 21
Andreas Wong Avatar answered Aug 26 '26 10:08

Andreas Wong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!