简单的二进制搜索树非递归添加功能

Simple Binary Search Tree Non recursive Add function

本文关键字:递归 添加 功能 搜索树 二进制 简单      更新时间:2023-10-16

我正在尝试编写一个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。