문제

I wrote the classes for BST,queue in C++. I have to traverse a BST in preorder manner, and add(put) values after traversing to the queue. Values are other class for segment (geometric objects). BST traversing and adding to the queue functions work seperately. However my values are not pushed into queue.
This is my code for traversing BST:

//Prefix traversal functions 
template <class T>
queue<T> Binary_tree <T>::prefix_trav(queue<T> abc, node *Bnode) {
    if (Bnode != NULL) {
        abc.addQ (Bnode - data);
        prefix_trav (abc, Bnode-leftChild);
        prefix_trav (abc, Bnode-rightChild);
    }
    return abc;
}
template <class T>
queue<T> Binary_tree <T>::prefix_trav() {
    queue<T> abc;
    abc = prefix_trav (abc, root);
    return abc;
}

Everytime i go through an element of a tree i add (put) it to the queue.

template (class T)
void queue<T>::addQ(T addData) {
    node *n = new node;
    n-data = addData;
    n-next = NULL;
    size++;
    if (isEmpty()) {
        first = n;
        last = n;
    } else {
        n-next = last;
        last = n;
    }
    cout<<"element "<<getSize()<<" has been added"<<endl;
}

But only root node is being addet to the queue.

도움이 되었습니까?

해결책

I think the problem is these lines:

if (Bnode != NULL) {
    abc.addQ (Bnode - data);
    prefix_trav (abc, Bnode-leftChild);
    prefix_trav (abc, Bnode-rightChild);
}
return abc;

You're traversing the left and right children, however this doesn't affect abc. What you should try is this:

if (Bnode != NULL) {
    abc.addQ (Bnode - data);
    abc = prefix_trav (abc, Bnode-leftChild);
    abc = prefix_trav (abc, Bnode-rightChild);
}
return abc;

But also, I notice you have Bnode-leftChild and Bnode-rightChild. This looks like a pointer subtraction to me - is this your intention? Should you be using -> instead of - ?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top