如何在 BST (C++) 中迭代计算节点数
How do you iteratively count nodes in a BST (C++)?
我已经知道如何递归地实现这个函数了。这是我所拥有的:
int nodeCount(node *root){
if(root == NULL)
return 0;
return 1 + nodeCount(root->left) + nodeCount(root->right);
}
我现在想在没有递归的情况下执行节点计数。
例如使用
stack
或queue
。
顺便说一句。你可能想看看尾递归维基页面。
int nodeCount(node * root)
{
int counter = 0;
stack<node*> v; // a container with remaining nodes "to check"
v.push(root); // first node "to check"
while (v.size() > 0) // while there is something "to check"
{
node * n = v.top(); // take element from the top of stack
v.pop(); // remove that element from the top of stack
if (n != NULL) // if node is valid
{
counter++; // count it
v.push(n->left); // and add
v.push(n->right); // his children to the stack
}
}
return counter;
}
相关文章:
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 对于C++随机访问迭代器(矢量迭代器),迭代器之间的差异是如何计算的?
- 自定义迭代器:如果 a 和 b 的行为不同,如何正确处理距离计算和相等比较
- 将多个计算放入使用基于迭代次数的变量的 for 循环中
- 特征:矩阵行的计算规范比在向量上迭代计算它们慢
- 迭代器,用于使用 C++ 计算 CSV 中的列数
- 当我计算它并给我 O(n^3) 时,这个迭代函数是如何是 O(n/2) 的
- 迭代排序列表并计算不同的数字
- 如何计算标准::矢量::<int>迭代器和标准::矢量<int>::reverse_iterator之间的距离?
- 如何使用 2 个迭代器进行求和函数计算映射<字符串、双精度>
- C++:计算每次迭代期间的概率百分比
- ranged-for 语句中的表达式是否在每次迭代时计算
- 在 c++ 中使用迭代器加速并行 std::vector 计算
- 如何在 BST (C++) 中迭代计算节点数
- 计算莱布尼茨求和的迭代次数,用于π C++
- C++:对迭代器之间计算距离的类型感到困惑
- 基于范围的 for 循环是否缓存容器表达式,或每次迭代重新计算它
- 迭代计算集合或向量的幂集
- 在for循环中,每次迭代计算向量的大小是否很昂贵
- OpenMP计算每个线程的循环迭代次数