Repository navigation
Expand file tree
/
Copy pathNodeBST.java
More file actions
63 lines (55 loc) · 1.56 KB
/
Copy pathNodeBST.java
File metadata and controls
63 lines (55 loc) · 1.56 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
package algorithms;
public class NodeBST {
NodeBST left, right;
int data;
public NodeBST(int data) {
this.data = data;
}
public void insert(int value) {
// look to the left and the right to see where we want to insert
if (value <= data) {
if (left == null) {
left = new NodeBST(value);
} else {
// push down to child and ask it to handle : recursion
left.insert(value);
}
} else {
if (right == null) {
right = new NodeBST(value);
} else {
right.insert(value);
}
}
}
public boolean contains(int value) {
// if we are there, return true
if (value == data) {
return true;
} else if (value < data) {
// then it should be on the left
// if there is no left node
if (left == null) {
return false;
} else {
return left.contains(value);
}
} else {
if (right == null) {
return false;
} else {
return right.contains(value);
}
}
}
// left child -> parent -> right child
public void printInOrder() {
if (left != null) {
left.printInOrder();
}
System.out.println("data = " + data);
if (right != null) {
right.printInOrder();
}
}
}