二叉搜索树"包含"功能

mha*_*190 2 c c++ binary-search-tree

尝试为二叉树创建包含函数.

该函数如下所示:

    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);
    }
}
Run Code Online (Sandbox Code Playgroud)

该函数对于实际位于树中的值返回false.有人可以帮忙吗?

谢谢,

马克斯

mad*_*tya 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);
  }
}
Run Code Online (Sandbox Code Playgroud)