forked from codehouseindia/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.java
More file actions
86 lines (86 loc) · 1.56 KB
/
bst.java
File metadata and controls
86 lines (86 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
java.util.Scanner;
class Bst
{
class Node
{
Node left;
int data;
Node right;
}
Node root;
Bst()
{
root=null;
}
public void insert(int data)
{
Node node;
node.data=data;
node.left=null;
node.right=null;
if(root==null)
root=node;
else if(root.data<data)
{
Node temp=root;
while(temp.data<data)
{
temp=temp.right;
if(temp==null)
temp=node;
}
while(temp.data>data)
{
temp=temp.left;
if(temp==null)
temp=node;
}
}
else if(root.data>data)
{
Node temp=root;
while(temp.data>data)
{
temp=temp.left;
if(temp==null)
temp=node;
}
while(temp.data<data)
{
temp=temp.right;
if(temp==null)
temp=node;
}
}
else System.out.println("Duplicate not allowed in tree");
}
public void display(Node root)
{
if(root==null)
return;
System.out.println(root.data);
display(root.left);
display(root.right);
}
}
class TestTree
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Bst tree=new Bst();
do {
System.out.println("Enter the element which you want to insert in tree");
int n;
n=sc.nextInt();
tree.insert(n);
System.out.println("Do you want to insert another element");
n=sc.nextInt();
boolean check;
if(n==1)
check=true;
else check=false;
} while (check);
tree.display(tree.root);
}
}