Java Reference
In-Depth Information
// Create a list containing the values from the tree in sequence
public LinkedList<T> sort() {
LinkedList<T> values = new LinkedList<>();
// Create a
linked list
treeSort(root);
// Sort the objects into the
list
return values;
}
// Extract the tree nodes in sequence
private void treeSort(Node node, LinkedList<T> values) {
if(node != null) {
// If the current node isn't
null
treeSort(node.left);
// process its left child node
// List the duplicate objects for the current node
for(int i = 0 ; i < node.count ; ++i) {
values.addItem(node.obj);
}
treeSort(node.right);
// Now process the right child
node
}
}
private Node root;
// The root node
// Private inner class defining nodes
private class Node {
Node(T value) {
obj = value;
count = 1;
}
T obj;
// Object stored in the node
int count;
// Count of identical objects
Node left;
// The left child node
Node right;
// The right child node
}
}
Directory "TryBinaryTree"
You can try out sorting integers and strings using BinaryTree<> objects with the following code:
public class TryBinaryTree {
public static void main(String[] args) {
int[] numbers = new int[30];
for(int i = 0 ; i < numbers.length ; ++i) {
Search WWH ::




Custom Search