簡體   English   中英

最大功能c樹高

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM