Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
最大函数c树高_C_Tree_Max - Fatal编程技术网

最大函数c树高

最大函数c树高,c,tree,max,C,Tree,Max,c中是否有一个max函数,我可以这样计算树高 :或者也许有更好的方法来计算树高 int height(struct node *tree) { if (tree == NULL) return 0; return 1 + max(height (tree->left), height (tree->right)); } 如果是,我需要什么 目前我收到了以下错误: dict tree.o:在函数“height”中: /home/ex10/dict tree.c:3

c中是否有一个max函数,我可以这样计算树高 :或者也许有更好的方法来计算树高

int height(struct node *tree)
{ 
    if (tree == NULL) return 0;
    return 1 + max(height (tree->left), height (tree->right)); 
}
如果是,我需要什么

目前我收到了以下错误:

dict tree.o:在函数“height”中:
/home/ex10/dict tree.c:36:未定义对“max”的引用


可能是因为max是一个未定义的函数

继续之前,请先尝试实现max

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

<>如果你愿意使用C++而不是纯C,那就有。它位于标准模板库中,因此您必须包含必需的文件。有关示例,请参见此处:

为方便起见:

// 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;
}
//max示例
#包括
#包括
使用名称空间std;
int main(){

cout不,没有内置函数。通常您会编写自己的内联函数,例如

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);
}
注意,谨防max宏陷阱。这很容易让人联想到

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

然后,您可以将其用于任何输入,而不管其类型如何,但这里的问题是,如果任何一个输入表达式都有副作用,例如,
MAX(++i,+++j)
。那么问题是,无论哪一个输入是最大值,副作用都将得到两次评估。如果要对MAX进行编码,则必须使用(内联)函数,而不是宏。unctothyy因为你在C没有C++没有重载/模板,这将限制你一个输入/输出类型的每一个命名max函数。< /p>

不存在。有一个函数的函数来计算最大值的浮点值(参见<代码>())/代码>和朋友们),您当然可以自己使用,但我认为只在本地使用更容易

比如:

const size_t left = height (tree->left);
const size_T right = height (tree->right);
return left > right ? left : right;
//在这种情况下,if else优于function max

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)); 
}