[英]max function c tree height
在c中有一个最大函数,所以我可以做这样的事情来计算树高:或者可能有更好的方法来计算树高。
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'的未定义引用
不,没有内置的。通常你会编写自己的内联函数,例如
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);
}
注意最大宏陷阱。 做某事很诱人
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
然后你可以将它用于任何输入而不管它们的类型,但问题是如果任何一个输入表达式都有副作用,例如MAX(++i, ++j)
。 那么问题是,无论哪个输入是最大值,副作用都会被评估两次。 如果要编写最大代码,则必须使用(内联)函数而不是宏。 不幸的是,由于你在C而不是C ++而没有重载/模板,这将限制你为每个命名的max函数设置一组输入/输出类型。
可能因为max是一个未定义的函数,
在继续之前尝试执行max。
int max(int a, int b) {
if(a > b) return a;
else return b;
}
不,没有。 有一系列函数来计算浮点值的最大值(参见fmax ()
和朋友),你当然可以自己使用它,但我认为在本地执行它更容易。
就像是:
const size_t left = height (tree->left);
const size_T right = height (tree->right);
return left > right ? left : right;
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));
}
//在这种情况下,如果else比函数max更好
如果你愿意使用C ++而不仅仅是普通的C,那就是。 它位于标准模板库中,因此您必须包含必需的文件。 请看这里的例子:
http://www.cplusplus.com/reference/algorithm/max/
为方便起见,转载:
// 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.