【发布时间】: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