tree code example
Example 1: binary tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
root = Node(1)
root.left = Node(2);
root.right = Node(3);
root.left.left = Node(4);
Example 2: TreeSet
// par défaut
TreeSet ensemble = new TreeSet();
// comparateur
Comparator comparateur = new Comparateur();
TreeSet ensemble = new TreeSet(comparateur);
// classe Comparateur implémentant l'interface Comparator
public class Comparateur implements Comparator {
public int compare(Object obj1, Object obj2){
return ((Comparable)obj2).compareTo(obj1);
}
public boolean equals(Object obj){
return this.equals(obj);
}
}
Example 3: tree
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
//if tree is empty, create root node
if(root == NULL) {
root = tempNode;
} else {
current = root;
parent = NULL;
while(1) {
parent = current;
//go to left of the tree
if(data < parent->data) {
current = current->leftChild;
//insert to the left
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
}
//go to right of the tree
else {
current = current->rightChild;
//insert to the right
if(current == NULL) {
parent->rightChild = tempNode;
return;
}
}
}
}
}
Example 4: tree
Trees are pretty POG
Example 5: TreeSet
// extrait de la classe TreeSet
public class TreeSet extends AbstractSet
implements SortedSet, Cloneable, java.io.Serializable {
//...
public TreeSet() {
this(new TreeMap());
}
//...
}
Example 6: treeset
TreeSet: Can contain only unique values and it is sorted in ascending order
TreeMap: Can contain only unique keys and keys are sorted in ascending order.