-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDeleteNodeFromBST
More file actions
34 lines (34 loc) · 795 Bytes
/
DeleteNodeFromBST
File metadata and controls
34 lines (34 loc) · 795 Bytes
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
class BST
{
Node findMax(Node root)
{
if(root == null)
return null;
if(root.right == null)
return root;
return findMax(root.right);
}
Node deleteNode(Node root, int key)
{
if(root == null)
return null;
if(key < root.key)
root.left = deleteNode(root.left, key);
else if(key > root.key)
root.right = deleteNode(root.right, key);
else
{
if(root.left == null)
return root.right;
else if(root.right == null)
return root.left;
else
{
Node temp = findMax(root.left);
root.key = temp.key;
root.left = deleteNode(root.left, root.key);
}
}
return root;
}
}