forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTreeExample.java
More file actions
85 lines (72 loc) · 1.63 KB
/
BinarySearchTreeExample.java
File metadata and controls
85 lines (72 loc) · 1.63 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
import java.util.*;
class Node{
int data;
Node left;
Node right;
public Node(int d){
data = d;
left = null;
right = null;
}
}
class BST{
Node head;
public BST(int d){
head = new Node(d);
}
public void addNode(Node h,Node n){
if(n.data < h.data){
if(h.left == null){
h.left = n;
return;
}
else
addNode(h.left,n);
}
else{
if(h.right == null){
h.right = n;
return;
}
else
addNode(h.right,n);
}
}
public void search(int d){
boolean found = false;
Node ptr = head; //Creating a pointer node, which will help us to find the element, initializing it from the head(searching drom the head)
while(ptr!=null){
if(ptr.data == d){
System.out.println("Yes, the element is present in the tree!");
found = true;
break;
}
else if(d > ptr.data)
ptr = ptr.right;
else
ptr = ptr.left;
}
if(!found)
System.out.println("Element not present!");
}
}
class BinarySearchTreeExample{
public static void main(String[] args){
int[] arr = {5,2,7,4,1,9}; //Example array
BST bst = new BST(arr[0]); //Setting the first element as the head of the binary search tree
for(int i=1;i<6;i++){
Node nodeToBeAdded = new Node(arr[i]);
bst.addNode(bst.head , nodeToBeAdded); // The elements of the array are added one by one
}
bst.search(4); //Let's search the Node with the value 4 in the bst we have created
bst.search(3);//Searching 3
bst.search(9);//Searching 9
bst.search(6);//Searching 6
/*Output:
Yes, the element is present in the tree!
Element not present!
Yes, the element is present in the tree!
Element not present!
*/
}
}