[英]Counting number of nodes less than X in BST
I have a code that is giving me these problems. 我有一个代码可以解决这些问题。 Can you give me some hint or guide about the mistake I am making, or any change that I should make? 您能否给我一些提示或指导,以说明我正在犯的错误或应该做出的任何更改? The errors are: 错误是:
BSTNode'<'Golfer'>' cannot be converted to BinarySearchTree'<'Golfer'>'. BSTNode'<'Golfer'>'无法转换为BinarySearchTree'<'Golfer'>'。
public int countLess (BinarySearchTree <Golfer> tree, int value) {
BSTNode<Golfer> node = tree.node;
if (node == null)
return 0;
int left = countLess(node.getLeft(), value);
int right = countRight(node.getRight(), value);
return (node.getInfo() > maxValue ? 1:0) + countLeft + countRight;
}
I think it should be something like this as i am guessing node.getLeft()
actually gives you a node in BST not the complete Left Subtree. 我认为应该是这样的,因为我猜到node.getLeft()
实际上在BST中为您提供了一个节点,而不是完整的Left Subtree。
public int countLess (BSTNode <Golfer> node, int value) {
if (node == null)
return 0;
int left = countLess(node.getLeft(), value);
int right = countLess(node.getRight(), value);
return (node.getInfo() > maxValue ? 1:0) + left + right;
}
Hope this solves your issue. 希望这能解决您的问题。 I can provide a more correct solution if you can share Implementation Of BinarySearchTree and BSTNode classes implementation. 如果可以共享BinarySearchTree的实现和BSTNode类的实现,则可以提供更正确的解决方案。
I think you should do an inorder traversal of the BST
. 我认为您应该对BST
进行有序遍历。 The inorder traversal of a BST
always gives you element in ascending order. BST
有序遍历始终为您提供按升序排列的元素。 Just keep a count
variable while doing inorder traversal (and keep incrementing it for each node visited), and as soon the value of any node becomes more than X, just 'break'. 只需在进行顺序遍历时保留一个count
变量(并为每个访问的节点保持递增),然后任何节点的值都超过X,就可以“中断”。
The final value in your count
variable will be the answer. 您的count
变量中的最终值将是答案。
BST: Binary Search Tree BST:二进制搜索树
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.