c++ - 用于计算 BST 中具有两个子节点的节点数的递归函数
问题描述
我需要实现这个递归函数,它将以 BST 为根,并递归计算其中有两个孩子的节点数,但我不确定我的逻辑是否正确?
我的逻辑是:
- 如果叶子或空,我们返回 0
- 您检查是否有两个孩子的节点我们添加一个并再次调用它的左右孩子
- 否则,如果一个节点没有两个子节点,则在其左右子树上调用而不添加
这是我的函数实现 ps:假设BinarySearchTree类中的所有内容都已实现:
int count(BinarySearchTree *root )
{
if(root== nullptr)
{
return 0;
}
if(root->right != nullptr and root->left!= nullptr)
{
return 1+count(root->right)+count(root->left);
}
count(root->right);
count(root->left);
}
解决方案
即使您的节点没有两个孩子,您也需要汇总计数。if 之后的两次 count 调用基本上没有被使用。你可以像这样修复它:
int count(BinarySearchTree *root )
{
if (root== nullptr)
{
return 0;
}
int countForThisNode = root->right != nullptr and root->left!= nullptr;
return countForThisNode + count(root->right) + count(root->left);
}
在这种情况下countForThisNode
,您要计算的节点为 1,否则为 0。无论如何,所有其他节点都会添加到结果中。
我希望这是您要的信息!
推荐阅读
- html - 引导程序使用 col-x 进行多种分辨率
- excel - 查找行中最后一次出现的值excel
- python - For循环不适用于在python中抓取Google搜索
- postgresql - 使用 Azure Kubernetes 将 Wiki.js 连接到现有 PostgreSQL 数据库
- jquery - 条件显示
- node.js - ReactJS,NodeJS,为我的应用程序使用一次性密码是否安全?
- java - JavaFX Connect 4 游戏获胜方法
- flutter - 如何将简单数据从`secondpage`发送到`mainpage`(有状态到有状态)
- javascript - 无法使用 React Hooks 渲染功能组件
- c# - 运行我的测试时无法在 ASP.NET 核心中调用 API DELETE (405 Method Not Allowed)。但它大摇大摆地工作