insert函数不断重新创建根节点

时间:2018-04-22 05:14:49

标签: c++ binary-search-tree

我试图创建一个非递归的insert()函数。我在书中唯一的例子是递归的,我试图转换它。这样你就可以了解我想要完成的事情,以及为什么我会包含这些说明。

编写一个类来实现一个能够存储数字的简单二进制搜索树。该类应具有成员函数:

void insert(double x)
bool search(double x)
void inorder(vector <double> & v)

insert函数不应该通过调用递归函数直接或间接使用递归。

还有更多,但我认为这给出了我所询问的背后的想法。截至目前,该函数只是继续重新创建根节点。这就是我所拥有的。

编辑:为了清晰起见,添加完整代码。

#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;
}

1 个答案:

答案 0 :(得分:0)

insert()方法中,您可以将传递的每个节点的值设置为新值。这可能不是你想要的。

如果要插入它,需要弄清楚它的位置,创建一个具有适当值的新节点,然后将新节点插入树中,小心处理以前的节点。