我正在尝试编写一个BST(),它将字符串作为节点而不使用递归。这是我的代码的添加功能,请您查看是否易于理解/遵循并指出错误。我是编程新手,非常感谢任何反馈。
#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;
}
};
}
答案 0 :(得分:0)
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
3 - 在“GetNewNode”中返回新节点而不是根
4 - 你的删除功能很乱,你应该再考虑一下并重新实现它。
最后,我强烈建议您检查并了解网上现成的实现,然后再尝试编写BST。