C++ 简单二叉搜索树非递归加法函数
我正在尝试编写一个BST(),它将字符串作为节点,而不使用递归。这是我的代码的add函数,请您复习一下,看看它是否容易理解/理解,并指出错误。我是编程新手,如有任何反馈,我将不胜感激C++ 简单二叉搜索树非递归加法函数,c++,insert,iteration,binary-search-tree,C++,Insert,Iteration,Binary Search Tree,我正在尝试编写一个BST(),它将字符串作为节点,而不使用递归。这是我的代码的add函数,请您复习一下,看看它是否容易理解/理解,并指出错误。我是编程新手,如有任何反馈,我将不胜感激 #include <iostream> #include <string> #include <stack> #include <queue> #include <fstream> #include <cstdlib> #include <
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main() {
class BST {
private:
struct Node {
string value;
Node* left;
Node* right;
};
Node* root;
public:
BST()
{
root = NULL;
}
~BST()
{
stack<Node*> nodes;
nodes.push( root);
while( ! nodes.empty())
{
Node* topNode = nodes.top();
nodes.pop();
if ( topNode->left )
nodes.push(topNode->left);
if ( topNode->right )
nodes.push(topNode->right);
delete topNode;
}
}
Node* GetNewNode(string data){
Node* newNode = new Node();
newNode->value=data;
newNode->left = newNode->right = NULL;
return root;
}
Node* Insert(Node* rootPtr,string data){
if(rootPtr == NULL){
rootPtr = GetNewNode(data);
return rootPtr;
}
else if(data<= rootPtr->value){
rootPtr->left = Insert(rootPtr->left,data);
}
else {
rootPtr->right = Insert(rootPtr->right,data);
}
return rootPtr;
}
};
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
BST级{
私人:
结构节点{
字符串值;
节点*左;
节点*右;
};
节点*根;
公众:
BST()
{
root=NULL;
}
~BST()
{
堆栈节点;
节点。推(根);
而(!nodes.empty())
{
Node*topNode=nodes.top();
nodes.pop();
如果(顶部节点->左侧)
节点。推送(topNode->left);
如果(顶部节点->右侧)
nodes.push(topNode->right);
删除topNode;
}
}
节点*GetNewNode(字符串数据){
Node*newNode=newNode();
新建节点->值=数据;
newNode->left=newNode->right=NULL;
返回根;
}
节点*插入(节点*rootPtr,字符串数据){
if(rootPtr==NULL){
rootPtr=GetNewNode(数据);
返回rootPtr;
}
else if(数据值){
rootPtr->left=插入(rootPtr->left,数据);
}
否则{
rootPtr->right=插入(rootPtr->right,数据);
}
返回rootPtr;
}
};
}
1-在插入功能中:
while (root != NULL) { // this shouldn't be root, the root isn't the node that traverse your tree, this has to be current
.....
}
2-您从不添加新节点,只需不断循环,直到达到空值。
您应该遍历树,直到找到插入节点的正确位置,然后添加新节点,如:
current = root;
prev = current;
while (current!= NULL) {
prev = current;
if (current->value.compare(word) < 0)
current = current->left;
else
current = current->right;
}
//here your new node should be on the left or the right of the prev node
current=root;
prev=当前值;
while(当前!=NULL){
prev=当前值;
如果(当前->值。比较(字)<0)
当前=当前->左侧;
其他的
当前=当前->右侧;
}
//在这里,新节点应该位于上一个节点的左侧或右侧
3-在“GetNewNode”中,返回新节点,而不是根节点
4-你的删除功能一团糟,你应该重新考虑并重新实现它
最后,我强烈建议您检查并理解来自web的现成实现,然后再次尝试编写BST 请正确缩进您的代码,它很难按原样读取。请提供可编译的代码。您好,上次我尝试编译代码时,代码确实已编译。您在问题中说,您希望“不使用递归”,但您显然在Insert函数中使用了递归(通过在Insert()中调用Insert())。你能解释一下吗?