Delete Node in Binary Search Tree Problem Statement

You are provided with a Binary Search Tree (BST) containing 'N' nodes with integer data. Your task is to remove a given node from this BST.

A BST is a binary tree with 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 left and right subtrees must also be binary search trees.

Input:

 T N1 L1 L2 ... LN D

Where:

  • T: Number of test cases.
  • Each test case consists of two lines:
    - First line: Tree elements in level order, '-1' specifies a null node.
    - Second line: Data of the node to delete.

Output:

Inorder traversal of the modified BST for each test case.

Example:

Input:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
5
Output:
4 2 1 6 3 7
Explanation:

After deleting the node with data 5, the inorder traversal of the BST is: 4 2 1 6 3 7.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 5000
  • 0 <= data <= 105

Time Limit: 1 second

Note:

  • The node to be deleted is guaranteed to be present in the tree.
  • If the tree becomes empty after deletion, the output should be -1.
  • No need to print the output; just implement the function.
  • For inorder traversal, visit the left subtree, then the node, and finally the right subtree.
Be the first one to answer
Add answer anonymously...
Times Internet Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter