Я создал BST с использованием C++. Функция отображения вызывает рекурсивно, и программа работает нормально.C++ BST - функция отображения вызова() без рекурсии
Однако я хочу показать BST без рекурсии. Как мне это достичь?
Вот мой код:
#include<iostream>
#include<fstream>
#include<time.h>
using namespace std;
struct Node {
int value;
Node * left;
Node * right;
};
Node * root;
class Tree{
public:
Tree() {
root = nullptr;
}
void _INSERT(Node * current, int data) {
if (current == nullptr) {
Node * temp = new Node;
temp->value = data;
temp->left = nullptr;
temp->right = nullptr;
root = temp;
}
else if (current->value == data)
return;
else if (current->value < data && current->right != nullptr)
_INSERT(current->right, data);
else if (current->value > data && current->left != nullptr)
_INSERT(current->left, data);
else if (current->value < data && current->right == nullptr) {
Node * temp = new Node;
temp->value = data;
temp->left = nullptr;
temp->right = nullptr;
current->right = temp;
}
else if (current->value > data && current->left == nullptr) {
Node * temp = new Node;
temp->value = data;
temp->left = nullptr;
temp->right = nullptr;
current->left = temp;
}
}
void _DISPLAY(Node * temp) {
if (temp != nullptr){
_DISPLAY(temp->left);
cout << temp->value << endl;
_DISPLAY(temp->right);
}
}
~Tree(){
root = nullptr;
}
};
int main() {
int value;
Tree obj;
ifstream inFile;
inFile.open("input.txt");
ofstream outFile;
outFile.open("input.txt");
srand(time(NULL));
for (int i = 0; i < 100; i++) {
value = (rand() % 500) + 1;
outFile << value << endl;
}
for (int i = 0; i < 100; i++){
inFile >> value;
obj._INSERT(root, value);
}
obj._DISPLAY(root);
system("pause");
return 0;
}
Я имею в виду, что мне нужно использовать стек. Если я нажимаю все узлы и когда самый левый узел имеет значение NULL, то выставляем значения.
Благодаря