计数BST中具有单个子节点的节点
Counting Nodes with single child in BST
我有这个问题:实现函数int countSingle(),它使用宽度优先遍历(BFT)来计算树中有多少节点有一个子节点。
所以下面的代码是我想到的解决它的方法,有没有另一种方法或者我错过的更有效的方法?
template <class T>
int BST<T>::countSingle()
{
QueueDLL<BSTNode<T>*> queue;
BSTNode<T>* node = root;
// If the tree is empty, there will be no nodes to traverse.
if(node == NULL) return -1;
// Initially, put the root in the queue
queue.Enqueue(node);
int counter = 0 ;
while(queue.IsEmpty() == false)
{
// Take a node out of the queue, process it and then insert
// its children into the queue.
node = queue.Dequeue();
// if the node has one only one child wether its the left or the right , increase counter
if((node->left == NULL && node->right != NULL) || (node->right== NULL && node->left!=NULL))
counter++;
if(node->left != NULL)
queue.Enqueue(node->left);
if(node->right != NULL)
queue.Enqueue(node->right);
}
return counter;
}
这看起来很好。你不能真正提高你所做的事情的复杂性,因为操作的数量是线性的。
几个实现要点:
-
计数是一个不可修改的操作,所以你可能要考虑
const
一些东西 -
你基本上已经实现了类似于编译器在递归中所做的事情。如果这是你的意图,那就太好了(还有一些性能点对你有利)。仅供参考,您可以使用极少loc的递归来完成此操作。
相关文章:
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 删除 XML 文件中的子节点C++
- 检查两个节点在子节点上是否具有相同状态的更优雅的方法
- 语言分析的二叉树实现 - 子节点:不起作用
- Node中的子节点列表在C++中的BFS遍历过程中丢失
- 根据 Pugixml 中的子值删除节点
- C++ 链表合并排序的实现在连接 1 个以上节点的子列表时失败
- C ,二进制树的高度,而不是检查我的子树是否为空,而是在检查我的子树是否是叶子节点.抛出分割故障
- c++ 无法从 XML 获取所有子节点
- 使用访问者设计模式在N- ARY树中重复访问子节点值
- TinyXML2 从节点和所有子节点获取文本
- C++ 访客模式与子类节点上的访客失去"is a"关系
- 遍历仅引用每个节点的子节点的树
- 从父节点中删除子节点 - PugiXML
- 根据其子节点的余额计算 AVL 树节点余额
- 有没有一种方便的方法可以从属性树中删除节点,同时保留其子节点
- 访问BST子节点时出现分段故障.为什么?
- 避免在节点中添加重复的子级,使用 Kasper Peeters 的 Tree.hh 库
- 结合二元算子AST节点的Boost Spirit Qi语法
- 对象中的对象从c++返回到节点(节点插件)