-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearchTree.java
115 lines (83 loc) · 1.99 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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package dataStructures;
public class BinarySearchTree //hetero.
{
static Node root;//root is dynamic pointer checks current node is root or leaf it does not mean parent
static class Node
{
int data;
Node leftAdd; //child linkage and parent detection
Node rightAdd;
Node(int data)
{
this.data=data;
}
}
static void insert(Node root,int data)
{
if(data<root.data)
{
if(root.leftAdd==null)
{
root.leftAdd=new Node(data);
System.out.println(data+" had been added towards left of "+root.data);
}
else
{
insert(root.leftAdd,data);
}
}
else if(data>root.data) // don't use else it will allow duplicates but bst does not allow duplicate
{
if(root.rightAdd==null)
{
root.rightAdd=new Node(data);
System.out.println(data+" had been added to right of "+root.data);
}
else
{
insert(root.rightAdd,data);
}
}
}
public static void inOrderTraversal(Node root)
{
if(root==null)
return;
inOrderTraversal(root.leftAdd);
System.out.print(root.data+" ");
inOrderTraversal(root.rightAdd);
}
public static void preOrderTraversal(Node root)
{
if(root==null)
return;
System.out.print(root.data+" ");
preOrderTraversal(root.leftAdd);
preOrderTraversal(root.rightAdd);
}
public static void postOrderTraversal(Node root)
{
if(root==null)
return;
postOrderTraversal(root.leftAdd);
postOrderTraversal(root.rightAdd);
System.out.print(root.data+" ");
}
public static void main(String[] args) {
Node root=new Node(50);
insert(root,10);
insert(root,20);
insert(root,15);
insert(root,40);
insert(root,3);
insert(root,40);
System.out.print("In Order -> ");
inOrderTraversal(root);
System.out.println();
System.out.print("pre Order -> ");
preOrderTraversal(root);
System.out.println();
System.out.print("post Order -> ");
postOrderTraversal(root);
}
}