遍历BST并输出到队列的前缀
Prefix traversing a BST with output to a queue
我为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-leftChild
和Bnode-rightChild
。在我看来,这就像是一个指针减法——这是你的意图吗?您应该使用->
而不是-
吗?
相关文章:
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Android NDK传感器向事件队列报告奇怪的间隔
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 按对象的特定方法按升序排列的C++优先级队列
- 使用2个键的cpp-stl::优先级队列排序不正确
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 在一个读写器队列中,我可以用volatile替换原子吗
- 为什么我的多线程作业队列崩溃
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 使用"Task"函数指针队列定义作业管理器
- 在c++队列中使用pop和visit实现线程安全
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 打印优先级队列
- 编译器如何在前缀和 postix 运算符之间进行区分?
- 共享队列的线程安全
- 带自定义比较器的最小优先级队列
- 在 Vulkan Qt 中获取队列系列
- 前缀表示法 C++,分段错误(堆栈和队列)
- 遍历BST并输出到队列的前缀