2013-08-06 52 views
2

試圖爲二叉樹製作一個包含函數。二分查找樹「包含」功能

功能如下:

bool contains(bt_node* top, int data) { 
    if (top == NULL) return false; 
    else { 
     if (data == top->data) return true; 
     else if (data < top->data) contains(top->left, data); 
     else if (data > top->data) contains(top->right, data); 
    } 
} 

功能對,實際上是在樹中的值返回false。誰能幫忙?

感謝,

最大

+0

編譯器是大約警告有關這樣的事情非常好。你打開了警告嗎? –

回答

5

你忘了遞歸調用的返回值來contains。所以你的函數的返回值是未定義的。它更改爲以下,使其工作:

bool contains(bt_node* top, int data) { 
    if (top == NULL) return false; 
    else { 
    if (data == top->data) 
     return true; 
    else if (data < top->data) 
     return contains(top->left, data);  //you forgot to return the value 
    else if (data > top->data) 
     return contains(top->right, data); 
    } 
} 
+0

Derrr。謝謝!我在寫信後意識到我沒有回來。 – mharris7190

0

你可能有小幅雖然做得更好:

bool contains(bt_node* top, int data) { 
    if (top == NULL) return false; 
    if (data == top->data) return true; 
    if (data < top->data) return contains(top->left, data);  
    return contains(top->right, data); 
}