[英]Get total count of nodes lesser/greater than some value in BST
我的代码有问题。 它显示:
BSTNode'<'Golfer'>' 不能转换成 BinarySearchTree'<'Golfer'>'。
请给我一些提示来修复我的代码。
public int countLowerScores(BinarySearchTree<Golfer> tree, int maxValue) {
BSTNode<Golfer> node = tree.root;
if (node == null) {
return 0;
}
int countLeft = countLowerScores(node.getLeft(), maxValue);
int countRight = countLowerScores(node.getRight(), maxValue);
return (node.getInfo() > maxValue ? 1 : 0) + countLeft + countRight;
}
我不知道BinarySearchTree
和BSTNode
有什么用,但你必须有相同类型的节点、左孩子和右孩子。
这就是树的全部思想,它是一个递归数据结构,这意味着可以以相同的方式处理 root 和 children。 下面是一个例子:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
和方法:
public int countLowerScores(TreeNode root, int maxValue) {
if (root == null) {
return 0;
}
int countLeft = countLowerScores(root.left, maxValue);
int countRight = countLowerScores(root.right, maxValue);
return (root.val > maxValue ? 1 : 0) + countLeft + countRight;
}
你用泛型使事情变得过于复杂。
您有将tree
作为参数的countLowerScores
方法。 现在你不能将节点传递给它。 您可以使用 BST Traversal 并通过每个节点集成并比较值。
public int countLowerScores(BinarySearchTree<Golfer> tree, int maxValue) {
Iterator<Golfer> iter; // Createts interator for comparision.
int count = 0; // Counts the number of nodes.
// Traverse the tree in inorder.
iter = tree.getIterator(BSTInterface.Traversal.Inorder);
// Get the nodes and compares to passed argument.
while (iter.hasNext()) {
if (iter.next().getScore() <= maxValue) {
count++;
};
}
return count;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.