I'm not sure why its not returning the minimum difference that can be found in the binary search tree. I cant debug nor use tester which has made it more difficult to find the issue.
Instrcutions:
Implement a method called getMinimumDifference() that takes in as parameter the root of a Binary Search Tree and returns an integer denoting the minimum absolute difference of any two distinct nodes within the Binary Search Tree.
Assumptions:
The node values in the binary search tree are greater than or equal to zero. All node values in the binary search tree are unique. The method will never receive the root of a tree that less than 2 nodes.
tree: [4,2,6,1,3]
4
2____||____6
1___||___3
expected output: 1
public static int getMinimumDifference(BTNode<Integer, Integer> root) {
int minHolder = 9;
BTNode<Integer, Integer> newNode = null;
recgmd(minHolder, root, newNode);
return minHolder;
}
public static void recgmd(int minHolder,BTNode<Integer, Integer> currentNode, BTNode<Integer, Integer> prevNode) {
if(currentNode == null) {
return;
}
recgmd(minHolder, currentNode.getLeftChild(), prevNode);
if(prevNode != null){
if(currentNode.getValue() - prevNode.getValue() <= minHolder) {
minHolder = currentNode.getValue() - prevNode.getValue();
}
}
prevNode = currentNode;
recgmd(minHolder, currentNode.getRightChild(), prevNode);
}
Description of how my code works:
Order: in-order
Why? To be able to compare between the previous node and the current one since they will be ascending order
>getMinimumDifference<
<Parameter>[root]
-[minHolder] Created variable that will be returned with the minimum difference found in BST.
-[newNode] Created node(will function as a prevNode) that will be compared with the current node on the helper method.
-Calls the helper, passing as parameters:[minHolder], [currentNode] and [prevNode].
>recgmd<
<Parameter>[minHolder] Variable that will be returned with the minimum difference found in BST.
<Parameter>[currentNode] Self-explanatory.
<Parameter>[prevNode] Self-explanatory.
-if the [currentNode] is null, returns
-recursive call to left child
-if its the first round(where [prevNode] is still null, skips)
--Otherwise, we check if the difference between the value of the [currentNode](which will always be greater than the later) and the [prevNode] is less than the value contained in [minHolder]
---if it is, the difference is saved in [minHolder]
----Otherwise, it continues
-[prevNode] is updated
-recursive call to left child