遍历BST并输出到队列的前缀

Prefix traversing a BST with output to a queue

本文关键字:队列 前缀 输出 BST 遍历      更新时间:2023-10-16

我为BST编写了类,在C++中排队。我必须以预购的方式遍历BST,并在遍历到队列后添加(放入)值。值是线段(几何对象)的其他类。BST遍历和添加到队列功能是分开工作的。然而,我的值并没有被推入队列
这是我遍历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;
}

每次我遍历树的一个元素时,我都会将它添加到队列中。

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;
}

但只有根节点被添加到队列中。

我认为问题在于这些行:

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

您正在遍历左右两个子项,但这不会影响abc。你应该试试这个:

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

但是,我注意到你有Bnode-leftChildBnode-rightChild。在我看来,这就像是一个指针减法——这是你的意图吗?您应该使用->而不是-吗?