【发布时间】:2018-10-04 12:59:23
【问题描述】:
我有一个Binary Search Tree,我需要得到 最接近的高点和 最接近的低点,而最近的低点必须在 5 到 9 之间(意思是高于5 或低于 9)。
假设我有一个 ID 为 125 的 Node,与该节点 最接近 的数字是 127,但它也必须在 5 到 9 之间,因此 ID 为 130 的“节点”会成为我正在寻找的人。
这是我正在使用的二叉树:
这就是我目前找到最接近的更高点的方式:
Node currentNode = null;
int currentNodeID;
double min = Double.MAX_VALUE;
public Node closestHigherValue(Node root, double target, int low, int high) {
min = Double.MAX_VALUE;
closestHigherHelper(root, target, low, high);
if(currentNodeID < (int) target) return null;
return currentNode;
}
public void closestHigherHelper(Node root, double target, int low, int high){
if(root==null)
return;
if(Math.abs(root.ID - target) < min && root.ID >target){
min = Math.abs(root.ID-target);
currentNodeID = root.ID;
//If between numbers
if(root.ID >= low && root.ID <= high) currentNode = root;
}
if(target < root.ID){
closestHigherHelper(root.leftChild, target, low, high);
} else {
closestHigherHelper(root.rightChild, target, low, high);
}
}
这一直有效。。在这里,我添加了可以在Binary Tree picture 上看到的所有节点,并开始寻找与某些值最近的点,然后一旦找到,就删除它们。 (删除工作正常)。
BinaryTree binaryTree = new BinaryTree();
binaryTree.add(130);
...
int[] IDArray = new int[]{125, 100, 120, 130};
for (int i = 0; i < IDArray.length; i++) {
Node closestHigher = binaryTree.closestHigherValue(binaryTree.root, IDArray[i], IDArray[i]+4, IDArray[i]+9);
System.out.println("Searching for" + IDArray[i] + " and Closest Value = "+ closestHigher.getID());
binaryTree.deleteNode(binaryTree.root, IDArray[i]);
}
这让我回来了:
Searching for 125 and Closest value = 130 //Should be 130
Searching for 100 and Closest value = null //Should be null
Searching for 120 and Closest value = 125 //Should be 125
Searching for 130 and Closest value = 125 //Should be 135 -- This one goes wrong
由于 closest lower 是相似的,因此无需显示该代码,我可以稍后修复此代码。
有什么想法吗?
【问题讨论】:
-
while being inside boundaries (between numbers 5 and 9)是什么意思? -
编辑问题以回答该问题
-
我认为你应该只更新
minif(root.ID >= low && root.ID <= high)。如需更多帮助,请发帖minimal reproducible example
标签: java binary-search-tree nodes