Allow traversing intervals
This commit is contained in:
parent
630a5c8acb
commit
e4c4da8fb9
1 changed files with 23 additions and 4 deletions
|
@ -52,7 +52,7 @@ public class TreeTraversal<T extends Comparable<T>> implements Traversal<T> {
|
|||
queue.add(root);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
TreeNode<T> node = queue.poll();
|
||||
TreeNode<T> node = queue.pop();
|
||||
|
||||
if (node.left != null) {
|
||||
queue.add(node.left);
|
||||
|
@ -67,8 +67,27 @@ public class TreeTraversal<T extends Comparable<T>> implements Traversal<T> {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void interval(T min, T max, Visitor<T> vistor) {
|
||||
// TODO Auto-generated method stub
|
||||
public void interval(T min, T max, Visitor<T> visitor) {
|
||||
Deque<TreeNode<T>> queue = new LinkedList<>();
|
||||
queue.add(root);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
TreeNode<T> node = queue.pop();
|
||||
|
||||
if (node != null) {
|
||||
T value = node.getValue();
|
||||
|
||||
if (value.compareTo(min) >= 0 && value.compareTo(max) <= 0) {
|
||||
visitor.visit(value);
|
||||
queue.add(node.left);
|
||||
queue.add(node.right);
|
||||
} else if (value.compareTo(max) > 0) {
|
||||
queue.add(node.left);
|
||||
}
|
||||
else if (value.compareTo(min) < 0) {
|
||||
queue.add(node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue