-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.java
91 lines (78 loc) · 2.18 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
public class BinarySearchTree {
Node root;
class Node{
int key;
Node left, right;
public Node(int item){
key = item;
left = right = null;
}
}
public BinarySearchTree(){
root = null;
}
public void insert(int key){
root = insertRec(root, key);
}
public Node insertRec(Node root, int key){
if(root == null){
root = new Node(key);
return root;
}
if(key < root.key)
root.left = insertRec(root.left, key);
else if(key > root.key)
root.right = insertRec(root.right, key);
return root;
}
public void intraversal(Node root){
if(root != null){
intraversal(root.left);
System.out.print(root.key + " ");
intraversal(root.right);
}
}
public Node FindMax(Node root){
if(root == null)
return null;
while (root != null) {
if (root.right != null)
root = root.right;
else
break;
}
return root;
}
public Node Delete(Node root, int data){
Node temp;
if(root == null)
System.out.printf("no such a element" + "\n" );
else if(data < root.key)
root.left = Delete(root.left, data);
else if(data > root.key)
root.right = Delete(root.right, data);
else{
if(root.right != null && root.left != null){
temp = FindMax(root.left);
root.key = temp.key;
root.left = Delete(root.left, root.key);
}else{
if(root.left == null)
root = root.right;
else if(root.right == null)
root = root.left;
}
}
return root;
}
public static void main(String[] args) {
BinarySearchTree bi = new BinarySearchTree();
bi.insert(5);
bi.insertRec(bi.root,7);
bi.insertRec(bi.root,1);
bi.insertRec(bi.root,3);
bi.insertRec(bi.root,6);
bi.Delete(bi.root,5);
bi.intraversal(bi.root);
}
}