我有一个Binary Search Tree
,我需要获得最近的最高价和最近的最低价,最近的最低价必须在5到9之间(这意味着高于5或低于9)。
让我们说我有一个ID为125的Node
,该节点的最近最高号为127,但它也必须介于5到9之间,因此ID为“ Node”的“ Node” 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
由于最接近的较低相似,因此无需显示该代码,并且在修复此代码后,我可以对其进行修复。
有什么想法吗?
答案 0 :(得分:1)
我认为您仅应在“边界”内更新min
,因此:
min = Math.abs(root.ID-target);
currentNodeID = root.ID;
//If between numbers
if(root.ID >= low && root.ID <= high) currentNode = root;
应该是
//If between numbers
if(root.ID >= low && root.ID <= high){
currentNode = root;
min = Math.abs(root.ID-target);
currentNodeID = root.ID;
}