是否计算二叉树中具有特定子级数量的节点

Count nodes with specific number of children in a binary tree?

本文关键字:节点 二叉树 计算 是否      更新时间:2023-10-16

我从一本关于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指出这一点