是否计算二叉树中具有特定子级数量的节点
Count nodes with specific number of children in a binary tree?
我从一本关于c++的书中得到了一个具有挑战性的练习,我不知道如何解决这个问题。我必须定义一个名为treeNodeCount()
的函数,它返回二叉树中的节点数(很容易),我还必须定义一种重载函数,它取一个表示子节点数的int(0,1,或2),并且该函数应该返回具有特定子节点数目的节点。treeNodeCount
都应该使用一个名为nodeCount(elemType root)
的函数来进行计数节点所需的递归(所以基本上所有的工作)。
第一个挑战是,我可以向nodeCount
添加第二个参数,它获取我们想要计数的节点的子节点数。
第二个挑战是我们不能使用第二个参数(这是困难的部分)
我能够完成挑战一,以下是我的想法:
template <class elemType>
int binaryTreeType<elemType>::nodeCount(nodeType<elemType> *p, int a ) const
{
if (p == NULL){
return 0;
}
else if (a == 0 && p->lLink == NULL && p->rLink == NULL){
return 1 + nodeCount(p->lLink, a) + nodeCount(p->rLink, a);
}
else if (a == 1 && (p->lLink != NULL ^ p->rLink != NULL)){
return 1 + nodeCount(p->lLink, a) + nodeCount(p->rLink, a);
}
else if (a == 2 && p->lLink != NULL && p->rLink != NULL){
return 1 + nodeCount(p->lLink, a) + nodeCount(p->rLink, a);
}
else if (a == -1){
return nodeCount(p->lLink, a) + nodeCount(p->rLink, a) + 1;
}
return nodeCount(p->lLink, a) + nodeCount(p->rLink, a);
}
template <class elemType>
int binaryTreeType<elemType>::treeNodeCount(int a) const{
return nodeCount(root, a);
}
这似乎很有效,但我相信必须有更好的方法。我没能完成挑战2,我不知道该怎么做(这可能吗)
您可以通过实现一个函数来返回给定节点的子级数量,从而简化逻辑并使其更加简单。
template <class elemType>
int nodeSize(nodeType<elemType>* node) const
{
int count = 0;
if (node->lLink)
++count;
if (node->rLink)
++count;
return count;
}
template <class elemType>
int binaryTreeType<elemType>::nodeCount(nodeType<elemType>* node, int count) const
{
if (node)
{
if (nodeSize(node) == count || count == -1)
return nodeCount(node->lLink, count) + nodeCount(node->rLink, count) + 1;
return nodeCount(node->lLink, count) + nodeCount(node->rLink, count);
}
return 0;
}
对于第二个挑战,您需要一个堆栈来避免递归。
template <class elemType>
int binaryTreeType<elemType>::treeNodeCount(int count) const
{
stack<nodeType<elemType>*> node_stack;
node_stack.push(root);
int num_matches = 0;
while (!stack.empty())
{
nodeType<elemType>* node = node_stack.top();
node_stack.pop();
if (node)
{
if (nodeSize(node) == count || count == -1)
++num_matches;
node_stack.push(node->lLink);
node_stack.push(node->rLink);
}
}
return num_matches;
}
编辑:修复了上述递归版本中的一个错误。感谢David Rodriguez指出这一点
相关文章:
- 指向二叉树中新节点的指针
- 将二叉树的节点插入链表 (C++)
- 如何在使用 ItemType 的模板类时将新节点插入二叉树 c++.(我是 c++ 的新手)
- 语言分析的二叉树实现 - 子节点:不起作用
- 重载运算符>>从二叉树中删除节点
- 打印具有空节点的二叉树
- 二叉树,从树中删除节点后将其删除
- 二叉树不接受新节点
- 连接二叉树中同一级别的节点
- 查找二叉树的父节点函数
- 程序设置二叉树,打印和搜索 - 节点类C++
- 查找二叉树中特定节点的深度
- 是否计算二叉树中具有特定子级数量的节点
- C++二叉树,修改根节点,指针到指针到根节点
- 创建一个函数,该函数返回一个新的相同二叉树,并向所有预先存在的叶添加新节点
- 如何在C++中合并二叉树的两个节点
- 找到最大路径总和,我们可以在二叉树中的任何节点开始和结束
- 给定一个二叉树,设计一个算法,创建每个深度的所有节点的链表
- 错误:请求"cur"中的成员"成员",该成员属于非类类型节点<int>* 二叉树
- 无法在二叉树中插入新节点