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