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?
我正在尝试实现一个函数,该函数计算二叉树中符合以下条件的节点:(节点>值%高度(<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 ) );
}
相关文章:
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 从值小于256的uint16到uint8的Endian安全转换
- 将stl字符串缩小到小于15个字符的容量
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 为什么我只能在C++中使用可变长度数组分配小于 10 mb 的内存?
- 如何为字符串生成唯一但一致的 N 位哈希(小于 64 位)?
- C++:如何根据地形高度更新玩家身高?
- 如何更改QComboBox项目的高度大小?
- 更改高度贴图,使其在 4x4 网格上显示 16 个 hieghtmap
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- sizeof(size_t) 可以小于 sizeof(int) 吗?
- C++:如何计算二叉树中其值模块高度小于 2 的节点数?
- unique_ptr < 0 或小于运算符做什么?
- 如何使用 C++ gdal 库将栅格地理从 EGM96 转换为 WGS84 椭球体高度基准面
- 从具有父指针和左子树和右子树高度的树中删除
- 程序输入名称和高度并显示它。我不知道如何显示列表中最高人的姓名和身高
- C++模板元编程(版本小于 17,最好是 11)
- 从小于或等于某个 N 的数字列表中最小化或找到 n 个理想的子集和
- 我正在尝试创建一个 C++ 贪吃蛇游戏,但我似乎无法绘制第二个高度边框,我该如何解决这个问题?
- 为什么 QFontMetrics::lineSpacing() 小于字符边界框的高度?