我试图实现一个简单的二进制搜索树,但我遇到了一些问题,我不知道这里的问题是什么。
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* left = NULL;
Node* right = NULL;
Node(int x):data(x)
{}
};
//BST Extends the Node class
class BST : public Node{
public:
Node* root = NULL;
//basic operations
void insertion(Node* root, int x);
void preorder(Node* root);
};
void BST::insertion(Node* root, int x) {
Node* newNode = new Node(x);
if(!root) {
root = newNode;
return;
}
if(x > root->data) BST::insertion(root->right, x);
if(x < root->data) BST::insertion(root->left, x);
}
void BST::preorder(Node* root) {
if(!root) return;
cout << root->data << " ";
BST::preorder(root->left);
BST::preorder(root->right);
}
int main() {
BST tree;
tree.insertion(tree.root, 8);
tree.insertion(tree.root, 6);
tree.insertion(tree.root, 12);
tree.insertion(tree.root, 10);
tree.preorder(tree.root);
return 0;
}
这些都是错误。
BST.cpp:46:6: error: use of deleted function 'BST::BST()'
BST tree;
^~~~
BST.cpp:17:7: note: 'BST::BST()' is implicitly deleted because the default definition would be ill-formed:
class BST : public Node{
^~~
BST.cpp:17:7: error: no matching function for call to 'Node::Node()'
BST.cpp:12:2: note: candidate: 'Node::Node(int)'
Node(int x):data(x)
^~~~
BST.cpp:12:2: note: candidate expects 1 argument, 0 provided
BST.cpp:6:7: note: candidate: 'constexpr Node::Node(const Node&)'
class Node{
^~~~
BST.cpp:6:7: note: candidate expects 1 argument, 0 provided
BST.cpp:6:7: note: candidate: 'constexpr Node::Node(Node&&)'
BST.cpp:6:7: note: candidate expects 1 argument, 0 provided
我检查了一些答案 但无法找出问题的根源 我认为是构造函数和数据成员的问题。
你没有给你的根节点一个值。
A BST
是一个 Node
和 Node
的唯一构造函数,期望有一个 int val
. 没有默认的构造函数--它已经被抑制了,或者用C++术语来说,"删除 "了。
你需要给 BST
类似的构造函数,将其传递给 Node
(或写 using Node::Node
继承它),以及你的声明。tree
在 main
需要提供一种价值。