【问题标题】:Simple Binary Search Tree Non recursive Add function简单二叉搜索树非递归添加函数
【发布时间】:2017-03-07 18:04:35
【问题描述】:

我正在尝试编写一个将字符串作为节点而不使用递归的 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;
    }
  };
}

【问题讨论】:

  • 能否请您正确缩进您的代码,很难按原样阅读。
  • 请提供可编译的代码。
  • 你好,我上次编译的时候确实编译成功了
  • 您在问题中说您想“不使用递归”来执行此操作,但您显然在 Insert 函数中使用了递归(通过在 Insert() 中调用 Insert())。你能解释一下吗?

标签: c++ insert iteration binary-search-tree


【解决方案1】:

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。

【讨论】:

    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2013-04-21
    • 1970-01-01
    • 2019-05-03
    • 2019-04-24
    • 2021-07-03
    相关资源
    最近更新 更多