0

Добрый день.

Хочу написать RRT, ну а для начала захотел написать обычное дерево, только чтобы указатели на правый и левый потомок хранились в векторе.

Пишу:

#include <iostream>
//#include <GL\freeglut.h>
#include <ctime>
#include <cmath>
#include <vector>
#include <iterator>

using namespace std ;

struct Node{

    int value ;
    vector <Node*> Children(2) ;

};

void Push(int info, Node *&tree){

    if(tree == NULL){

        tree = new Node ;
        tree -> value = info ;
        tree -> Children[0] = NULL ;
        tree -> Children[1] = NULL ;

    }

    if(info > tree -> value){

        Push(info, tree -> Children[1]) ;

    }

    if(info < tree -> value){

        Push(info, tree -> Children[0]) ;

    }

}

void Show(Node *&tree){

    if(tree != NULL){
        Show(tree -> Children[0]) ;
        cout << tree -> value << " " ;
        Show(tree -> Children[1]) ;
    }

}

int main(){

    Node *tree = NULL ;
    int x ;

    for (int i = 0; i < 7 ; i++){
        cout << "Put : " ;
        cin >> x ;
        Push(x, tree) ;
        cout << endl ;
    }

    Show(tree) ;

    return 0 ;
}

Ошибки:

expected unqualified-id before numeric constant в структуре.

invalid types ' unresolved overloaded function type int ' for array subscript в каждой функции.

Помогите разобраться. В векторах я новичок, поэтому ошибки могут оказаться тривиальными, заранее спасибо за понимание.

Обновление

Как я понял: vector <Node*> Children(2) - не стоило так делать. Надо было vector <Node*> Children ;.

Но теперь как обращаться к потомкам?

1 ответ 1

1

Первую ошибку Вы уже исправили. Осталось исправить ещё одну.

if(tree == NULL){
    tree = new Node ;
    tree -> value = info ;
tree->Children.resize(2); // эта строка добавляет два элемента.
    tree -> Children[0] = NULL ;
    tree -> Children[1] = NULL ;
}

А можно и так было сделать:

if(tree == NULL){
    tree = new Node ;
    tree -> value = info ;
    tree->Children.push_back(NULL);
    tree->Children.push_back(NULL);
}

Правильно ли оно работает - я не знаю.

В этом коде есть ещё хорошая утечка памяти. Объект то создаете, а удалять - забываете.

1
  • Спасибо, вслед за вашим решение придумал другое: в структуру дописать выделение. struct Node{ int value ; vector <Node*> Children ; Node(): Children(2) {} }; 16 мар 2015 в 8:34

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.