C++:如何计算二叉树中其值模块高度小于 2 的节点数?

C++: How do I count the number of nodes in a binary tree for which its value module its height is minor to 2?

本文关键字:小于 高度 模块 节点 何计算 二叉树 计算 C++      更新时间:2023-10-16

我正在尝试实现一个函数,该函数计算二叉树中符合以下条件的节点:(节点>值%高度(<2 我知道它一定是一个递归函数,我尝试实现它如下:

int count(Node* tree, int h=1){
if (!tree) return 0;
if ((tree->value%h)<2)
return count(tree->left, h++) + count(tree->right, h++) + 1;
else
return count(tree->left, h++) + count(tree->right, h++);
}

这个功能不起作用,我不明白我的错误在哪里。我将不胜感激你能给我的任何帮助。提前谢谢。

与语句

return count(tree->left, h++) + count(tree->right, h++) + 1;

您正在递增h,这意味着其中一个计数调用的值可能高于另一个。实际上,这是未定义的行为,因为两个h++的评估顺序没有定义。

写。。。

return count(tree->left, h+1) + count(tree->right, h+1) + 1;

这样的调用

count(tree->left, h++) + count(tree->right, h++)
^^^                       ^^^ 

具有未定义的行为。

函数可以通过以下方式定义

size_t count( const Node *tree, size_t h = 0 )
{
return tree == nullptr ? 0
: ( ++h, ( tree->value % h < 2 ) +
count( tree->left, h ) + count( tree->right, h ) );
}