您好,有人建议我学习非递归地编写东西,以便更清楚地了解程序中发生的事情。它是一个二进制搜索程序,它读取总统列表的 .dat 文件并按字母顺序对它们进行排序。这是我要使其成为非递归的代码:
BstNode* Insert(BstNode* root, string data) {
if (root == NULL) {
root = GetNewNode(data);
}
else if (data <= root->data) {
root->left = Insert(root->left, data);
}
else {
root->right = Insert(root->right, data);
}
return root;
}
我想了解什么是递归,以及如何看待递归的东西并使其成为非递归的。我很难理解这些概念。如果我使该部分非递归,我不确定是否需要调整二叉搜索树的其余部分。
这是完整的程序,以防您需要查看其他情况:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct BstNode {
string data;
BstNode* left;
BstNode* right;
};
BstNode* GetNewNode(string data) {
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
BstNode* Insert(BstNode* root, string data) {
if (root == NULL) {
root = GetNewNode(data);
}
else if (data <= root->data) {
root->left = Insert(root->left, data);
}
else {
root->right = Insert(root->right, data);
}
return root;
}
bool Search(BstNode* root, string data) {
if (root == NULL) return false;
else if (root->data == data) return true;
else if (data <= root->data) return Search(root->left, data);
else return Search(root->right, data);
}
void Print(BstNode*x) {
if (!x) return;
Print(x->left);
cout << ' ' << x->data << endl;
Print(x->right);
}
int main() {
BstNode* root = NULL; //creating an empty tree
//root = Insert(root, "adam"); test
//root = Insert(root, "greg"); test
//root = Insert(root, "tom"); test
//root = Insert(root, "bill"); test
//root = Insert(root, "sarah"); test
//root = Insert(root, "john"); test
ifstream fin;
fin.open("prez.dat");
string currentprez;
string input = "";
while (!fin.eof()) {
fin >> currentprez;
root = Insert(root, currentprez);
}
for (;;) {
string input = "";
cout << "Would you like to 'search', 'insert', 'print' or 'quit'?\n";
cin >> input;
//if user searches
if (input == "search" || input == "Search") {
string searchstr = "";
cout << "Enter string to be searched: \n";
cin >> searchstr;
if (Search(root, searchstr) == true) cout << searchstr + " was Found\n";
else cout << "Not Found\n";
}
//if user inserts
else if (input == "insert" || input == "Insert") {
string insertstr = "";
cout << "Enter string to be inputted: \n";
cin >> insertstr;
if (Search(root, insertstr) == true) cout << insertstr + " already exists\n";
else root = Insert(root, insertstr);
}
//if user prints
else if (input == "print" || input == "Print") Print(root);
//if user quits
else if (input == "quit" || input == "Quit") return(0);
//if anything else
else cout << "Invalid input\n";
}
}