Close
Topic list
Delete Node In BST
MEDIUM
10 mins
Binary Search Trees
Topics (Covered in this problem)
Problem solved
Skill meter
Binary Search Trees
-
-
Other topics
Problem solved
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

# Delete Node In BST

Contributed by
Prashansa
Medium
0/80
Avg time to solve 10 mins
Success Rate 90 %
Share

## Problem Statement

#### A binary search tree (BST) is a binary tree data structure which has the following properties.

``````• The left subtree of a node contains only nodes with data less than the node’s data.
• The right subtree of a node contains only nodes with data greater than the node’s data.
• Both the left and right subtrees must also be binary search trees.
``````
##### Example:
``````For the given BST, if we want to delete the node with data 5 :
``````

``````The modified BST will be:
``````

``````Please notice that another valid answer is:
``````

#### Note :

``````1. The node which we want to delete will always be present in the given tree.

2. If after deletion the tree becomes empty, print -1.
``````
Detailed explanation ( Input/output format, Notes, Constraints, Images )
##### Sample Input 1:
``````1
20 -1 -1
20
15 10 20 8 12 16 25 -1 -1 -1 -1 -1 -1 -1 -1
10
``````
##### Sample output 1:
``````-1
8 12 15 16 20 25
``````
##### Explanation of Sample output 1:
``````In test case 1, there is only one node with the value 20, thus after deleting it the tree would be empty.

In test case 2, the tree can be represented as follows:
``````

``````After the deletion of the node with data 10 the BST will be:
``````

``````The inorder traversal of this modified BST is 8 12 15 16 20 25.

Another valid modified BST can be:
``````

``````The inorder traversal of this modified BST is also 8 12 15 16 20 25.
``````
##### Sample Input 2:
``````2
10 5 -1 -1 -1
5
6 4 -1 -1 5
6
``````
##### Sample output 2:
``````10
4 5
``````
##### Explanation of Sample Output 2:
``````In test case 1, there are only two nodes in the Binary Search Tree and we are deleting the node with value 5. Thus the only node left will the node with value 10.

In test case 2, the tree can be represented as follows:
``````

``````After the deletion of the node with data 6 the BST will be:
``````

``````The inorder traversal of this modified BST is 4 5.
``````
Auto
Console