简单的二进制搜索树非递归添加功能
Simple Binary Search Tree Non recursive Add function
我正在尝试编写一个bst(),该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;
}
};
}
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"中返回新节点,而不是root
4-您的删除功能是一团糟,您将再次考虑并重新实现。
最后,我强烈建议您检查并了解网络上的现成实现,然后尝试再次编写您的BST。
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 递归添加子树以提升属性树
- 编写递归算法以从链表中删除元素.编写递归算法以将元素添加到链表中
- 如何在Qt中递归添加源文件
- 递归地将 1 添加到 BST 中的所有节点,但具有最小数据的节点除外
- 简单的二进制搜索树非递归添加功能
- c++ 递归添加,4*x
- 如何使用递归向字符串添加逗号
- 递归函数,添加传递给它的两个变量
- 将目录添加到Xcode自定义项目模板会产生奇怪的递归
- 使用递归将元素添加到向量中
- 递归添加到带有点 c++ 的向量
- 用内部类函数递归地添加数组数
- 递归-按顺序向列表中添加树数据
- 将基数10转换为12,在递归地添加字母字符时遇到麻烦
- 递归函数扫描字符串以添加ASCII
- 以递归方式将项添加到矢量
- QTDom -递归地向特定元素添加子元素
- 为什么添加相同的东西会翻转递归