[英]Simple Binary Search Tree Non recursive Add function
我正在嘗試編寫一個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”中返回新節點而不是根節點
4-您的刪除功能一團糟,您將再次考慮並重新實現它。
最后,我強烈建議您從網上檢查並了解現成的實現,然后嘗試再次編寫BST。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.