forked from rathoresrikant/HacktoberFestContribute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree.java
105 lines (86 loc) · 1.91 KB
/
Tree.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
import java.util.*;
class Node {
Node left;
Node right;
int data;
Node(int data) {
this.data = data;
this.right = this.left = null;
}
}
class BinaryTree {
Node root;
BinaryTree() {
root = null;
}
void add(int key) {
root = insert(root, key);
}
Node insert(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.data)
root.left = insert(root.left, key);
else if (key > root.data)
root.right = insert(root.right, key);
return root;
}
void display() {
print(root);
}
// A utility function to do inorder traversal of BST
void print(Node root) {
if (root != null) {
print(root.left);
System.out.println(root.data);
print(root.right);
}
}
void del(int key)
{
root = delete(root, key);
}
Node delete(Node root, int key)
{
if (root == null)
return root;
if (key < root.data)
root.left = delete(root.left, key);
else if (key > root.data)
root.right = delete(root.right, key);
else
{
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
root.data = small(root.right);
root.right = delete(root.right, root.data);
}
return root;
}
int small(Node root)
{
int min = root.data;
while (root.left != null)
{
min = root.left.data;
root = root.left;
}
return min;
}
}
class Tree {
public static void main(String[] args) {
BinaryTree s = new BinaryTree();
s.add(50);
s.add(60);
s.add(70);
s.add(80);
s.display();
s.del(60);
s.display();
}
}