简体   繁体   中英

binary search tree “contains” function

Trying to make a contains function for a binary tree.

The function looks like this:

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

The function is returning false for a value that actually is in the tree. Can anyone help?

Thanks,

Max

You forgot to return the value of the recursive calls to contains . So the return value of your function is undefined. Change it to the following to make it work:

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

You could have done slightly better though:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM