1+ /**
2+ * Deletion_of_a_node_in_bst
3+ */
4+ public class Deletion_of_a_node_in_bst {
5+ class Node {
6+ int key ;
7+ Node left , right ;
8+
9+ Node (int item ) {
10+ key = item ;
11+ left = right = null ;
12+ }
13+ }
14+
15+ Node root ;
16+
17+ Deletion_of_a_node_in_bst () {
18+ root = null ;
19+ }
20+
21+ void deleteKey (int key ) {
22+ root = deleteRec (root , key );
23+ }
24+
25+ Node deleteRec (Node root , int key ) {
26+ if (root == null )
27+ return root ;
28+ if (key < root .key )
29+ root .left = deleteRec (root .left , key );
30+ else if (key > root .key )
31+ root .right = deleteRec (root .right , key );
32+ else {
33+ if (root .left == null )
34+ return root .right ;
35+ else if (root .right == null )
36+ return root .left ;
37+
38+ root .key = minValue (root .right );
39+ root .right = deleteRec (root .right , root .key );
40+ }
41+ return root ;
42+ }
43+
44+ int minValue (Node root ) {
45+ int minv = root .key ;
46+ while (root .left != null ) {
47+ minv = root .left .key ;
48+ root = root .left ;
49+ }
50+ return minv ;
51+ }
52+
53+ void insert (int key ) {
54+ root = insertRec (root , key );
55+ }
56+
57+ Node insertRec (Node root , int key ) {
58+ if (root == null ) {
59+ root = new Node (key );
60+ return root ;
61+ }
62+ if (key < root .key )
63+ root .left = insertRec (root .left , key );
64+ else if (key > root .key )
65+ root .right = insertRec (root .right , key );
66+ return root ;
67+ }
68+
69+ void inorder () {
70+ inorderRec (root );
71+ }
72+
73+ void inorderRec (Node root ) {
74+ if (root != null )
75+ inorderRec (root .left );
76+ System .out .print (root .key + " " );
77+ inorderRec (root .right );
78+
79+ }
80+
81+ public static void main (String [] args ) {
82+ Deletion_of_a_node_in_bst tree = new Deletion_of_a_node_in_bst ();
83+ // * Let us create following BST
84+ // ? 50
85+ // ? / \
86+ // ? 30 70
87+ // ? / \ / \
88+ // ?20 40 60 80 */
89+ tree .insert (50 );
90+ tree .insert (30 );
91+ tree .insert (20 );
92+ tree .insert (40 );
93+ tree .insert (70 );
94+ tree .insert (60 );
95+ tree .insert (80 );
96+
97+ System .out .println ("Inorder traversal of the given tree" );
98+ tree .inorder ();
99+
100+ System .out .println ("\n Delete 20" );
101+ tree .deleteKey (20 );
102+ System .out .println ("Inorder traversal of the modified tree" );
103+ tree .inorder ();
104+
105+ System .out .println ("\n Delete 30" );
106+ tree .deleteKey (30 );
107+ System .out .println ("Inorder traversal of the modified tree" );
108+ tree .inorder ();
109+
110+ System .out .println ("\n Delete 50" );
111+ tree .deleteKey (50 );
112+ System .out .println ("Inorder traversal of the modified tree" );
113+ tree .inorder ();
114+ }
115+ }
0 commit comments