Maximum function c tree height

is there a max function in c, so I can do something like this to calculate the height of the tree: or maybe there is a better way to calculate the height of the tree.

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

if so, what do I need?

I am currently getting this error:

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

+3
source share
5 answers

Probably since max is an undefined function,

try running max first before continuing.

int max(int a, int b) {
    if(a > b) return a;
    else return b;
}
+2
source

No, there is no built-in device. Usually you should write your own built-in function, for example

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

( "" , ). , , - :

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. . . -

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

, , , . MAX(++i, ++j). , , , . max, () , . , C ++ /, / max.

+7

No no. There are many functions for calculating the maximum floating point value (see fmax()friends), which you can certainly use on your own, but it seems to me that it is easier to do this locally.

Sort of:

const size_t left = height (tree->left);
const size_T right = height (tree->right);
return left > right ? left : right;
+2
source

If you want to use C ++, and not just C, there is. This is in the standard template library, so you have to include the required file. See here for an example:

http://www.cplusplus.com/reference/algorithm/max/

Reproduced for your convenience:

// max example
#include <iostream>
#include <algorithm>
using namespace std;

int main () {
  cout << "max(1,2)==" << max(1,2) << endl;
  cout << "max(2,1)==" << max(2,1) << endl;
  cout << "max('a','z')==" << max('a','z') << endl;
  cout << "max(3.14,2.72)==" << max(3.14,2.72) << endl;
  return 0;
}
0
source
int height(struct node *tree)
{ 
if (tree == NULL) 
{
    return 0;
}    
int left = height(tree->left);
int right = height(tree->right);
return (1 + ((left >right)?left:right)); 
}

// if else is better than the max function in this case

0
source

Source: https://habr.com/ru/post/1792542/


All Articles