gpt4 book ai didi

c++ - 二叉搜索树实现(C++)

转载 作者:太空宇宙 更新时间:2023-11-04 15:22:09 25 4
gpt4 key购买 nike

大部分代码来自Weiss的《Data structures and algorithm analysis in C++》,我在CodeBlock(gnu,gcc)上敲代码后,编译器没有报错,但后来我尝试创建一个实例并测试一些函数出错了。 BST() 或 insert() 似乎有问题,因为程序自运行后立即卡住。 有人会帮我找出解决这个问题的方法吗?非常感谢!!!

#include <iostream>
using namespace std;
struct TreeNode
{
int element;
TreeNode*left,*right;
TreeNode(const int&e,TreeNode*le=NULL,TreeNode*rt=NULL):element(e),left(le),right(rt){};
};

class BST
{
public:
BST(){root=NULL;};
~BST(){ makeEmpty(root); };
// use public member function to call private member functions.
void insert(const int & x){ insert(x, root); }
void remove(const int & x){ remove(x, root); }
TreeNode*findMin() const{ return findMin(root); }
bool contain(const int & x) const{ return contain(x,root); }
void printNodes() const{ printNodes(root); }

private:
TreeNode*root;

void makeEmpty(TreeNode*&);
TreeNode* findMin(TreeNode*) const;
void insert(const int &, TreeNode*) const;
void remove(const int &, TreeNode*) const;
bool contain(const int &, TreeNode*) const;
void printNodes(TreeNode*) const;
};

void BST::makeEmpty(TreeNode*&t)
{
if(t!=NULL)
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t=NULL;
}
TreeNode* BST::findMin(TreeNode*t) const
{
if(t->left==NULL) return t;
return findMin(t->left);
}
void BST::insert(const int & x, TreeNode* t) const
{
if(t==NULL) t=new TreeNode(x,NULL,NULL);
else if(x < t->element) insert(x,t->left);
else if(x > t->element) insert(x,t->right);
else; /// duplicate, do nothing
}
void BST::remove(const int & x, TreeNode* t) const
{
if(t==NULL) return;
if(t->element > x) remove(x, t->left);
else if(t->element < x) remove(x, t->right);
else if(t->left!=NULL && t->right!=NULL)
{
t->element=findMin(t->right)->element;
remove(t->element,t->right);
}
else
{
TreeNode*oldNode=t;
t=(t->left==NULL)?t->right:t->left;
delete oldNode;
}
}
bool BST::contain(const int & x, TreeNode*t) const
{
if(t==NULL) return false;
else if(x<t->element) return contain(x,t->left);
else if(x>t->element) return contain(x,t->right);
else return true;
}
void BST::printNodes(TreeNode*t) const
{
if(t==NULL) return;
cout<<t->element<<" ";
printNodes(t->left);
printNodes(t->right);
cout<<endl;
};

这是我为测试类 BST 编写的代码:

int main()
{
BST BinarySearchTree;
int element,node;
for(int i=0; i<5; i++)
{
cin>>element;
BinarySearchTree.insert(element);
}
BinarySearchTree.printNodes();

cout<<BinarySearchTree.findMin()->element<<endl;

cin>>node;
if(BinarySearchTree.contain(node)){ cout<<"item "<<node<<" is in BST."<<endl; }

BinarySearchTree.remove(node);
BinarySearchTree.printNodes();
return 0;
}

最佳答案

你的类 BST 只有一个成员变量。 树节点*根。 (这没有问题)

您的insertremove 函数可能修改 BST,因此您需要修改root 相关的事情

(出于同样的原因,您的编译器会很快指出这些函数不应该是 const。)

关于c++ - 二叉搜索树实现(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16207204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com