Files
2025-07-21 16:03:34 +02:00

114 lines
2.4 KiB
Java

/**
* An ordered binary tree.
*
* @author Marcus
*/
public class Tree {
/**
* The root node of the tree.
*/
private TreeNode root;
/**
* Creates a new and empty tree.
*/
public Tree() {
super();
}
/**
* Traverses the tree and calls the visitor's
* visit(TreeNode) method in pre-order.
*
* @param visitor The visitor whose visit method
* shall be called in pre-order.
*/
public void traverse(TreeVisitor visitor) {
traverse(visitor, root);
}
/**
* Traverses the subtree starting at current
* and calls the visitor's visit(TreeNode)
* method in pre-order.
*
* @param visitor The visitor.
* @param current The subtree to visit, may be null.
*/
private void traverse(TreeVisitor visitor, TreeNode current) {
if (current == null) return;
// TODO: implement
}
/**
* Inserts a new value into the true.
*
* @param value The value to insert.
*/
public void insert(double value) {
if (root == null) {
root = new TreeNode(value);
} else {
insert(value, root);
}
}
/**
* Recursively finds the right node to insert the
* value and inserts it.
*
* @param value The value to insert.
* @param current The current value.
*/
private void insert(double value, TreeNode current) {
if (value <= current.getValue()) {
// smaller or equal values go left
if (current.getLeft() == null) {
current.setLeft(new TreeNode(value));
} else {
insert(value, current.getLeft());
}
} else {
// larger values go right
if (current.getRight() == null) {
current.setRight(new TreeNode(value));
} else {
insert(value, current.getRight());
}
}
}
/**
* Efficiently counts the number of nodes in the
* tree that have a particular value by considering
* the order that is defined by the tree's insert
* method.
*
* @param value The value to search from.
* @return The number of nodes with the value.
*/
public int count(double value) {
return count(value, root);
}
/**
* Efficiently counts the number of nodes in the
* subtree starting at current that have a particular
* value by considering the order that is defined
* by the tree's insert method.
*
* @param value The value to search from.
* @param current The subtree to search in, may be null.
* @return The number of nodes with the value.
*/
private int count(double value, TreeNode current) {
if (current == null) return 0;
// TODO: implement
return -1;
}
}