【发布时间】:2020-05-18 18:34:00
【问题描述】:
我正在尝试实现一个简单的二叉搜索树,但我遇到了一些问题,我无法弄清楚这里有什么问题。
#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
我检查了几个答案,但无法找出导致问题的原因,我认为这是构造函数和数据成员的问题
【问题讨论】:
-
insertion()和preorder()泄漏新分配的本地根,并留下 BST 的rootnull。
标签: c++ c++11 c++14 binary-search-tree