【发布时间】:2021-12-04 03:02:54
【问题描述】:
我需要遍历二叉搜索树并找到第 n 个项目,我能够成功地遍历树,但是当我尝试实现限制或端点时,停止在 nth 项目 -返回它的值,我不能让我的计数器增加。我已经尝试了大约 50 种不同的方法来让计数器增加但无济于事。
我目前将计数器实现为类属性,因此它不在递归函数的单个调用范围内。为了帮助我进行故障排除和学习,我尝试让它打印出节点处的值以及位置,这就是我意识到我的计数器不会增加的原因。
想要的结果:
10 (position 1)
25 (position 2)
32 (position 3)
...
当前结果:
10 (position 1)
25 (position 1)
32 (position 1)
...
这是我的课:
class BST {
public:
int data;
int counter = 0;
BST *left, *right;
BST();
BST(int);
~BST();
void insert(int val);
int nth_node(int n);
int size();
};
还有我的 nth_node 函数:
int BST::nth_node(int n) {
/*
// Check to see if we've hit the limiter.
if (counter == n) {
std::cout << std::endl<< std::endl << "ITEM FOUND!!!" << std::endl<< std::endl;
counter = 0; //reset the counter
return data;
} */
if (counter <= n) { // Haven't hit the limiter, so do in_order transversal
// Go left
if (left != nullptr){
left -> nth_node(n);
}
// Go middle
counter++;
std::cout << data << " (position: " << counter << "), " << std::endl ;
// Go Right
if (right != nullptr){
right -> nth_node(n);
}
}
return data;
}
【问题讨论】:
标签: c++ data-structures binary-tree binary-search-tree recursive-datastructures