-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTree.java
89 lines (76 loc) · 2.16 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
85
86
87
88
89
class Node {
int value;
Node left, right;
public Node(int item) {
value = item;
left = right = null;
}
}
class BinaryTree {
Node root;
// Insert a new value into the binary tree
void insert(int value) {
root = insertRec(root, value);
}
Node insertRec(Node root, int value) {
if (root == null) {
root = new Node(value);
return root;
}
if (value < root.value) {
root.left = insertRec(root.left, value);
} else if (value > root.value) {
root.right = insertRec(root.right, value);
}
return root;
}
// Search for a value in the binary tree
boolean search(int value) {
return searchRec(root, value);
}
boolean searchRec(Node root, int value) {
if (root == null) {
return false;
}
if (root.value == value) {
return true;
}
// return value < root.value ? searchRec(root.left, value) : searchRec(root.right, value);
// Maybe a little more clear.
if (value < root.value) {
return searchRec(root.left, value);
} else {
return searchRec(root.right, value);
}
}
// In-order traversal of the binary tree
void inOrder() {
inOrderRec(root);
}
void inOrderRec(Node root) {
if (root != null) {
inOrderRec(root.left);
System.out.print(root.value + " ");
inOrderRec(root.right);
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
// Insert values
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
tree.insert(24);
tree.insert(99);
// Print in-order traversal
System.out.println("In-order traversal:");
tree.inOrder();
// Search for a value
int searchValue = 80;
System.out.println("\nSearching for " + searchValue + ": " + (tree.search(searchValue) ? "Found" : "Not Found"));
}
}