This is a homework assignment. I need to recursively traverse through a binary search tree, to find out if a node’s data value falls in a range (inclusive), and print them out in ascending order.
My thought process goes: To print the data value out in ascending order, I need to do in-order traversal on the search tree. To traverse efficiently, if a node’s left child is less than the lower value, and the node’s data is less than the lower value, the program should stop traverse to the left. On the same token, if a node’s right child is larger than the upper value, and the node’s data is more than the upper value, the program should stop traverse to the right.
So here goes my implementation, with error:
public void rangeSearch(int lower, int upper) {
if (lower > upper)
throw new IllegalArgumentException("lower > upper");
if (root != null)
rangeSearchTree(root, lower, upper);
}
private static void rangeSearchTree(Node root, int lower, int upper) {
Node leftChild = root.left;
Node rightChild = root.right;
if (leftChild != null && root.key > lower) {
root = leftChild;
rangeSearchTree(root, lower, upper);
}
if (root.key >= lower && root.key <= upper) {
System.out.print(root.key + " ");
}
if (rightChild != null && root.key < upper) {
root = rightChild;
rangeSearchTree(root, lower, upper);
}
}
The tree has structure of:
7
/ \
5 9
/ \ /
2 6 8
\
4
When I enter 6 for lower bound value and 9 for upper bound value, I get 6 8 8. The correct answer should be 6 7 8 9. Any suggestions?
You are changing the
rootin the middle of the code. Therootthat you evaluate in the secondifis not the one passed as a parameter but its left child…