【问题标题】:Prefix traversing a BST with output to a queue遍历 BST 并输出到队列的前缀
【发布时间】:2014-06-08 18:27:21
【问题描述】:

我用 C++ 为 BST 和队列编写了类。 我必须以预排序方式遍历 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;
}

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

【问题讨论】:

    标签: c++ queue binary-search-tree


    【解决方案1】:

    我认为问题出在以下几行:

    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。这对我来说看起来像是一个指针减法 - 这是你的意图吗?您应该使用-&gt; 而不是- 吗?

    【讨论】:

    • 非常感谢,这有帮助。是的,它是和箭头->,我只是不知道如何放置“>”符号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多