将矢量中的对象插入二叉树中

时间:2016-03-21 07:54:54

标签: c++ vector binary-search-tree

所以我有一个BST.cpp和BST.h 我已经去了一个创建和插入功能

BST::node* BST::createLeaf(int value)
{
    node* newNode = new node;
    newNode -> value = value;

    //make sure left and right are pointing to null
    newNode->left = NULL;
    newNode->right = NULL;

    return newNode;
}

void BST::insert(int value, node * Ptr)
{
    if (root == NULL)
    {
        root = createLeaf(value);
    }

    //if tree is not empty
    else if (value < Ptr->value)
    {
        //go left, but check if it's pointing to something first
        if (Ptr->left != NULL)
        {
            //if yes, recursively move down the left side
            insert(value, Ptr->left);
        }
        //else if it's not pointing to anything
        else
        {
            //add mode tree
            Ptr->left = createLeaf(value);
        }
    }

我想读一个包含10个数字的.txt文件,将其存储在一个向量中,然后将这些数字放入二叉树中。

{
    vector<int> numbers;

    //Create an input file stream
    ifstream in("treeValues.txt",ios::in);


    int number;

    //Read number using the extraction (>>) operator
    while (in >> number) {
        //Add the number to the end of the array
        numbers.push_back(number);
    }

    //Close the file stream
    in.close();

    //Display the numbers to test
    cout << "Numbers:\n";
    for (int i=0; i<numbers.size(); i++) {
        cout << numbers[i] << " ";
    }

    //add these numbers to the tree

    for (int i = 0; i <numbers.size(); i++)
    {
        myTree.insert(numbers[i]);
    }


    cin.get(); //Keep program open until "enter" is pressed

}

它没有用,所以我想知道问题是什么?是否有另一种方法将读取整数从文件存储到节点中?我甚至需要矢量吗?

谢谢!

0 个答案:

没有答案