1import java.util.Iterator;
2import java.util.TreeSet;
3public class TreeSetIteratorMethodExample
4{
5 public static void main(String[] args)
6 {
7 TreeSet<Integer> ts = new TreeSet<Integer>();
8 ts.add(23);
9 ts.add(52);
10 ts.add(63);
11 ts.add(21);
12 // create ascending iterator
13 Iterator<Integer> iterate = ts.iterator();
14 // print TreeSet
15 System.out.println("TreeSet in ascending order: ");
16 while(iterate.hasNext())
17 {
18 System.out.println(iterate.next() + " ");
19 }
20 }
21}
1package MyPackage;
2
3public class Tree {
4 static class Node {
5 int value;
6 Node left, right;
7
8 Node(int value){
9 this.value = value;
10 left = null;
11 right = null;
12 }
13 }
14
15 public void insert(Node node, int value) {
16 if (value < node.value) { if (node.left != null) { insert(node.left, value); } else { System.out.println(" Inserted " + value + " to left of " + node.value); node.left = new Node(value); } } else if (value > node.value) {
17 if (node.right != null) {
18 insert(node.right, value);
19 } else {
20 System.out.println(" Inserted " + value + " to right of "
21 + node.value);
22 node.right = new Node(value);
23 }
24 }
25 }
26 public void traverseInOrder(Node node) {
27 if (node != null) {
28 traverseInOrder(node.left);
29 System.out.print(" " + node.value);
30 traverseInOrder(node.right);
31 }
32 }
33
34 public static void main(String args[])
35 {
36 Tree tree = new Tree();
37 Node root = new Node(5);
38 System.out.println("Binary Tree Example");
39 System.out.println("Building tree with root value " + root.value);
40 tree.insert(root, 2);
41 tree.insert(root, 4);
42 tree.insert(root, 8);
43 tree.insert(root, 6);
44 tree.insert(root, 7);
45 tree.insert(root, 3);
46 tree.insert(root, 9);
47 System.out.println("Traversing tree in order");
48 tree.traverseLevelOrder();
49
50 }
51}
1// java treeset example
2import java.util.Iterator;
3import java.util.TreeSet;
4public class TreeSetExamples
5{
6 public static void main(String[] args)
7 {
8 TreeSet<String> ts = new TreeSet<String>();
9 ts.add("red");
10 ts.add("blue");
11 ts.add("green");
12 ts.add("red");
13 Iterator<String> iterate = ts.iterator();
14 while(iterate.hasNext())
15 {
16 System.out.println(iterate.next());
17 }
18 }
19}
1import java.util.*;
2
3// Declare the variable using the interface of the object for flexibility.
4// Non-primative data types only.
5Set<String> movies = new TreeSet<String>();
6
7movies.add(E);
8// TreeSet will be sorted by element.
9// Work with any comparable object.
10
11movies.add("The Shining");
12movies.add("Dawn of the Dead");
13movies.add("Zombieland");
1// extrait de la classe TreeSet
2public class TreeSet extends AbstractSet
3 implements SortedSet, Cloneable, java.io.Serializable {
4 //...
5 public TreeSet() {
6 this(new TreeMap());
7 }
8 //...
9}