如何解决通过递归查找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());
}
,
尝试
FF
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。