-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearchTree.java
49 lines (49 loc) · 1.14 KB
/
BinarySearchTree.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
package fastds;
public class BinarySearchTree {
Node root;
BinarySearchTree(){
root=null;
}
private class Node{
Node left;
int data;
Node right;
public Node(int x){
left=right=null;
data=x;
}
}
public void display(){
print(root);
}
public void insert(int x){
root=insert(x,root);
}
public boolean isFound(int x){
Node trav=root;
while(trav!=null){
if(trav.data==x)
return true;
else if(x < trav.data)
trav=trav.left;
else
trav=trav.right;
}
return false;
}
private Node insert(int y,Node root){
if(root==null) return new Node(y);
else if(y <=root.data)
root.left=insert(y,root.left);
else
root.right=insert(y,root.right);
return root;
}
private void print(Node root){
if(root!=null){
print(root.left);
System.out.println(" "+root.data);
print(root.right);
}
}
}