【发布时间】:2018-04-22 16:54:34
【问题描述】:
我正在尝试创建一个非递归的 insert() 函数。我在书中唯一的例子是一个递归的例子,我正在尝试转换它。只是为了让您了解我要完成的工作以及我为什么要包含这些说明。
编写一个类来实现一个能够存储数字的简单二叉搜索树。类应该有成员函数:
void insert(double x)
bool search(double x)
void inorder(vector <double> & v)
插入函数不应直接或通过调用递归函数间接使用递归。
还有更多,但我认为这给出了我所问问题背后的想法。截至目前,该功能只是继续重新创建根节点。这是我所拥有的。
#include "stdafx.h"
#include <iostream>
#include <vector>
class BinaryTree {
private:
struct TreeNode {
double value;
TreeNode *left;
TreeNode *right;
TreeNode(double value1,
TreeNode *left1 = nullptr,
TreeNode *right1 = nullptr) {
value = value1;
left = left1;
right = right1;
}
};
TreeNode *root; //pointer to the root of the tree
bool search(double x, TreeNode *t) {
while (t) {
std::cout << "running through t." << std::endl;
if (t->value == x) {
return true;
}
else if (x < t->value) {
std::cout << "wasn't found, moving left." << std::endl;
search(x, t->left);
}
else {
std::cout << "wasn't found, moving right." << std::endl;
search(x, t->right);
}
}
std::cout << "wasn't found." << std::endl;
return false;
}
public:
std::vector<TreeNode> v;
BinaryTree() {
root = nullptr;
}
void insert(double x) {
TreeNode *tree = root;
if (!tree) {
std::cout << "Creating tree." << x << std::endl;
root = new TreeNode(x);
return;
}
while (tree) {
std::cout << "Adding next value." << std::endl;
if (tree->value == x) return;
if (x < tree->value) {
tree = tree->left;
tree->value = x;
}
else {
tree = tree->right;
tree->value = x;
}
}
}
bool search(double x) {
return search(x, root);
}
/*void inOrder(TreeNode *v) const {
while (root != nullptr) {
inOrder(root->left);
v.push_back(root->value);
inOrder(root->right);
v.push_back(root->value);
}
}*/
};
int main() {
BinaryTree t;
std::cout << "Inserting the numbers 5, 8, 3, 12, and 9." << std::endl;
t.insert(5);
t.insert(8);
t.insert(3);
t.insert(12);
t.insert(9);
std::cout << "Looking for 12 in tree." << std::endl;
if (t.search(12)) {
std::cout << "12 was found." << std::endl;
}
std::cout << "Here are the numbers in order." << std::endl;
return 0;
}
【问题讨论】:
-
while (tree)的任何地方都没有创建新节点。坏juju会发生。 -
我添加了 cout 语句来查看它是如何运行的。它永远不会进入 while 循环。这就是我感到困惑的地方。
标签: c++ insert binary-search-tree