-
Notifications
You must be signed in to change notification settings - Fork 1
/
Node.java
89 lines (73 loc) · 2.25 KB
/
Node.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 key;
Node left;
Node right;
public Node(int key) {
this.key = key;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
private Node root;
public BinarySearchTree() {
this.root = null;
}
public void insert(int key) {
root = insertRec(root, key);
}
private Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key) {
root.left = insertRec(root.left, key);
} else if (key > root.key) {
root.right = insertRec(root.right, key);
}
return root;
}
public boolean search(int key) {
return searchRec(root, key);
}
private boolean searchRec(Node root, int key) {
if (root == null || root.key == key) {
return root != null;
}
if (key < root.key) {
return searchRec(root.left, key);
}
return searchRec(root.right, key);
}
public void inorderTraversal() {
inorderTraversalRec(root);
}
private void inorderTraversalRec(Node root) {
if (root != null) {
inorderTraversalRec(root.left);
System.out.print(root.key + " ");
inorderTraversalRec(root.right);
}
}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);
System.out.println("Inorder Traversal of the Binary Search Tree:");
bst.inorderTraversal(); // Output: 20 30 40 50 60 70 80
int searchKey = 40;
System.out.println("\nSearching for key " + searchKey + " in the Binary Search Tree:");
boolean found = bst.search(searchKey);
if (found) {
System.out.println("Key " + searchKey + " found in the Binary Search Tree.");
} else {
System.out.println("Key " + searchKey + " not found in the Binary Search Tree.");
}
}
}