java - 通过递归查找 BST 的大小
问题描述
尝试在链接的 BST 中递归查找大小(总对象)。得到奇怪的错误回报,不完全确定为什么。
private int size(BinaryTreeNode<T> root)
{
if (root == null) // empty tree
return 0;
if (root.getRight() == null && root.getLeft() == null) // base case, only root node exists
return 1;
else if (root.getRight() == null && root.getLeft() != null) // only left node exists
return size(root.getLeft()) + 1;
else if (root.getRight() != null && root.getLeft() == null) // only right node exists
return size(root.getRight()) + 1;
else
return size(root.getRight()) + size(root.getLeft()) + 1; // right and left nodes exist
}
查找树的大小时:
< 33 >
1 > < 67 >
12 > 1 80
13
我得到 1 作为返回大小而不是 6。
解决方案
您的代码看起来正确,但可以简化为。
private int size(BinaryTreeNode<T> root)
{
if (root == null) // empty tree
return 0;
return 1 + size(root.getLeft()) + size(root.getRight());
}
推荐阅读
- python - 将pandas DataFrame中的元组旋转到特定的行元素
- azure - 使用 powershell 检查群集磁盘上的可用空间
- entity-framework - 为什么实体框架核心不支持原始 sql 查询?
- php - 嵌套多维数组中最低级别的总和
- docker - 由于 EADDRNOTAVAIL,Fluent-bit 无法将日志发送到 docker 中的 fluentd
- javascript - 不知道如何使用本地存储和 jquery 解决这个问题
- html - 如何提高 CSS 动画性能
- python - 什么样的图像尺寸适合 MaskRCnn?
- sql - 从 SQL 查询中过滤数据
- amazon-web-services - AWS IAM 策略仅允许对具有特定标签的资源执行角色删除操作