Печать значений C ++ в векторном двоичном дереве после вставки - PullRequest
0 голосов
/ 05 мая 2018

Мне поручено хранить двоичное дерево внутри вектора. Внутри каждого узла хранятся int ID, int Age и строковое имя.

Узлы хранятся и организуются в векторе по идентификатору.

При сохранении двоичного дерева в векторе я использую алгоритм 2i и 2i + 1, чтобы продиктовать левый и правый потомок узла соответственно.

Мне удалось создать метод вставки, который, по моему мнению, удовлетворяет этим условиям, однако по какой-то причине при попытке напечатать значения моего вектора я получаю отрицательные значения. Для этого конкретного примера я вставляю следующие значения

50 21 Тим

75 22 Стив

30 40 Эрик

20 35 Мэри

100 60 Джуди

После вставки этих четырех значений я пытаюсь использовать метод find (), чтобы найти Эрика, в котором моя программа возвращает «Not Found!»

Я запускаю функцию report (), чтобы обнаружить, что все значения, хранящиеся в моем векторе, являются большими отрицательными идентификаторами.

Есть ли для этого особая причина? Find () Отчет ()

Вот мой код.

#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
int index = 0;

struct Node
{
    int ID;
    int age;
    string name;

    Node()
    {

    }

    Node(int id, int Age, string nm)
    {
        this->ID = id;
        this->age = Age;
        this->name = nm;
    }
};

vector<Node> binaryTree(30);


BST::BST()
{

}



void BST::start()
{
    int choice;


    cout << "What would you like to do?" << endl;
    cout << "1. Add a node to the tree" << endl;
    cout << "2. Delete a node from the tree" << endl;
    cout << "3. Find a node in the tree" << endl;
    cout << "4. Report the contents of the tree" << endl;
    cout << "5. Exit program" << endl;

    cin >> choice;

    if (choice == 1)
    {
        insert();
    }

    if (choice == 2)
    {
        Delete();
    }

    if (choice == 3)
    {
        find();
    }

    if (choice == 4)
    {
        report();
    }


}


void BST::insert()
{
    int ID;
    int AGE;
    string NAME;
    int root = 1;

    bool success = false;
    cout << "Please enter the ID number, age and name:" << endl;

    do
    {
        cin >> ID >> AGE >> NAME;
    } while (ID < 0);

    Node *tree = new Node(ID, AGE, NAME);


    if (index = 0)
    {
        binaryTree[1] = *tree;
    }

    if (index > 0)
    {
        do
        {
            if (tree->ID > binaryTree.at(root).ID)
            {
                root = 2 * root + 1;

            }

            if (tree->ID < binaryTree.at(root).ID)
            {
                root = 2 * root;
            }

            if (binaryTree.at(root).ID == NULL)
            {
                binaryTree.at(root) = *tree;
                success = true;
            }
        } while (!success);
    }

    index++;
    delete tree;

    start();
}





void BST::Delete()
{
    int input_id;
    cout << "What is the ID of the person to be deleted" << endl;
    cin >> input_id;

    for (unsigned int i = 0; i < binaryTree.size(); i++)
    {
        if (input_id == binaryTree.at(i).ID)
            binaryTree.erase(binaryTree.begin() + i);


    }
    cout << " " << endl;
    start();
}


void BST::find()
{
    int key;
    bool found = 0;

    cout << "What's the ID?" << endl;
    cout << " " << endl;

    cin >> key;

    for (unsigned int i = 0; i < binaryTree.size(); i++)
    {
        if (binaryTree.at(i).ID == key)
        {
            cout << "The ID is " << binaryTree.at(i).ID << endl;
            cout << "The age ID " << binaryTree.at(i).age << endl;
            cout << "The name is " <<binaryTree.at(i).name << endl;
            cout << " " << endl;

            found = true;

        }
        if (found == false)
        {
            cout << "Not found." << endl;
            cout << "" << endl;
            break;
        }
    }
    start();
}


void BST::report()
{

    cout << "The contents of the tree are" << endl;
    cout << " " << endl;

    for (unsigned int i = 0; i < binaryTree.size(); i++)
    {
        int level = 0;
        if (i == 0) level = 0;
        if (i == 1 || i == 2) level = 1;
        if (i >= 3 && i <= 6) level = 2;
        if (i >= 7 && i <= 14) level = 3;
//TODO complete list
        cout << binaryTree.at(i).ID << " " << binaryTree.at(i).age << " " << &binaryTree.at(i).name << " " << level << endl;

    }
}

Буду признателен за предложения / помощь!

Спасибо!

1 Ответ

0 голосов
/ 05 мая 2018

Я думаю, что проблемы с индексацией здесь В insert() вы создали двоичное дерево с корнем в индексе, но в функции report() вы начали вывод с индекса 0. Я понятия не имею, что делает binaryTree.at(int).

Но в find() ваша ошибка связана с тем, что вы включили if (found == 0) в цикл. Это означает, что он прервет цикл, если 1-й элемент дерева не является элементом, который вы ищете. Используйте этот код вместо

void BST::find()
{
    int key;
    bool found = 0;

    cout << "What's the ID?" << endl;
    cout << " " << endl;

    cin >> key;

    for (unsigned int i = 0; i < binaryTree.size(); i++)
    {
        if (binaryTree.at(i).ID == key)
        {
            cout << "The ID is " << binaryTree.at(i).ID << endl;
            cout << "The age ID " << binaryTree.at(i).age << endl;
            cout << "The name is " <<binaryTree.at(i).name << endl;
            cout << " " << endl;

            found = true;

        }
    }
    if (found == false)
    {
        cout << "Not found." << endl;
        cout << "" << endl;
    }
    start();
}
...