-
Notifications
You must be signed in to change notification settings - Fork 11
/
BST_Insertion.java
42 lines (34 loc) Β· 974 Bytes
/
BST_Insertion.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
package trees;
import java.util.Scanner;
public class BST_Insertion {
public static void main(String[] args) {
Tree<Integer> root = new Tree<>();
root.input();
root.print();
Scanner s = new Scanner(System.in);
int data = s.nextInt();
root = insert(root, data);
System.out.println();
root.print();
}
private static Tree insert(Tree<Integer> root, int data){
if(root == null){
Tree<Integer> obj = new Tree<>(data);
return obj;
}
if(data < root.data){
if(root.left != null) insert(root.left, data);
else {
root.left = new Tree<>(data);
return root;
}
} else {
if(root.right != null) insert(root.right, data);
else {
root.right = new Tree<>(data);
return root;
}
}
return root;
}
}