-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.java
84 lines (68 loc) · 2.05 KB
/
BinaryTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
*
* @author José Rodrigo Barrera García
* Universidad del Valle
* Este codigo fue tomado del ejemplo brindado por Douglas
* Como tambien se tomo como referencia la siguiente pagina:
* https://www.baeldung.com/java-binary-tree
*
* @param <E>
*/
public class BinaryTree<E extends Comparable<E>> {
Node<E> root;
private Node<E> addRecursive(Node<E> current, E value) {
if (current == null) {
return new Node<E>(value);
}
if (value.compareTo(current.getValue()) < 0) {
current.right = addRecursive(current.right, value);
} else if (value.compareTo(current.getValue()) > 0) {
current.left = addRecursive(current.left, value);
} else {
// value already exists
return current;
}
return current;
}
public void add(E value) {
root = addRecursive(root, value);
}
public Node<E> locateRecursive(Node<E> root, E value)
{
E rootValue = root.getValue();
Node<E> child;
// found at root: done
if (rootValue.compareTo(value) == 0) return root;
// look left if less-than, right if greater-than
if (value.compareTo(rootValue) < 0)
{
child = root.right;
} else {
child = root.left;
}
// no child there: not in tree, return this node,
// else keep searching
if (child == null) {
return null;
} else {
return locateRecursive(child, value);
}
}
public Node<E> locate(E value){
return locateRecursive(root, value);
}
private void printInorderRecursive(Node<E> node)
{
if (node == null)
return;
/* first recur on left child */
printInorderRecursive(node.right);
/* then print the data of node */
System.out.print(node.getValue().toString());
/* now recur on right child */
printInorderRecursive(node.left);
}
public void printInorder(){
printInorderRecursive(root);
}
}