forked from joeyajames/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.java
More file actions
125 lines (111 loc) · 3.39 KB
/
bst.java
File metadata and controls
125 lines (111 loc) · 3.39 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Java Binary Search Tree
public class Tree {
Node root;
public boolean insert(int val) {
if (root == null) {
root = new Node(val);
return true;
}
else
return root.insert(val);
}
public boolean find(int val) {
if (root == null)
return false;
else
return root.find(val);
}
public void preorder() {
if (root != null) {
System.out.println("Preorder:");
root.preorder();
}
}
public void postorder() {
if (root != null) {
System.out.println("Postorder:");
root.postorder();
}
}
public void inorder() {
if (root != null) {
System.out.println("Inorder:");
root.inorder();
}
}
private class Node {
private Node leftChild;
private Node rightChild;
private int data;
private Node(int val) {
data = val;
}
private boolean insert(int val) {
boolean added = false;
if (this == null) {
this.data = val;
return true;
}
else {
if (val < this.data) {
if (this.leftChild == null) {
this.leftChild = new Node(val);
return true;
}
else
added = this.leftChild.insert(val);
}
else if (val > this.data) {
if (this.rightChild == null) {
this.rightChild = new Node(val);
return true;
}
else
added = this.rightChild.insert(val);
}
}
return added;
}
private boolean find(int val) {
boolean found = false;
if (this == null)
return false;
else {
if (val == this.data)
return true;
else if (val < this.data && this.leftChild != null)
found = this.leftChild.find(val);
else if (val > this.data && this.rightChild != null)
found = this.rightChild.find(val);
}
return found;
}
private void preorder() {
if (this != null) {
System.out.println(this.data);
if (this.leftChild != null)
this.leftChild.preorder();
if (this.rightChild != null)
this.rightChild.preorder();
}
}
private void postorder() {
if (this != null) {
if (this.leftChild != null)
this.leftChild.postorder();
if (this.rightChild != null)
this.rightChild.postorder();
System.out.println(this.data);
}
}
private void inorder() {
if (this != null) {
if (this.leftChild != null)
this.leftChild.inorder();
System.out.println(this.data);
if (this.rightChild != null)
this.rightChild.inorder();
}
}
}
}