
Problem
Solution
Submissions
Binary Search Tree with Insert and Delete Operations
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a Python program to implement a Binary Search Tree (BST) with insert and delete operations. A Binary Search Tree is a node-based binary tree data structure that has the following properties: the left subtree contains only nodes with keys less than the node's key; the right subtree contains only nodes with keys greater than the node's key; and both left and right subtrees are also binary search trees.
Algorithm for BST class
- Define a TreeNode class to represent nodes in the BST.
- Implement insertion by traversing the tree to find the correct position.
- Implement search by comparing values and traversing left or right accordingly.
- Implement deletion handling three cases: no children, one child, two children.
- Implement tree traversal methods using a recursive approach.
Example 1
- Input: ["BST", "insert", "insert", "insert", "search", "delete", "search", "inorderTraversal"] [[], [5], [3], [7], [3], [3], [3], []]
- Output: [null, null, null, null, true, null, false, [5, 7]]
- Explanation:
- bst = BST()
- bst.insert(5) // Insert 5
- bst.insert(3) // Insert 3
- bst.insert(7) // Insert 7
- bst.search(3) // Returns true as 3 exists
- bst.delete(3) // Delete 3
- bst.search(3) // Returns false as 3 is deleted
- bst.inorderTraversal() // Returns [5, 7]
Example 2
- Input: ["BST", "insert", "insert", "insert", "insert", "delete", "preorderTraversal"] [[], [10], [5], [15], [3], [10], []]
- Output: [null, null, null, null, null, null, [5, 3, 15]]
- Explanation:
- bst = BST()
- bst.insert(10) // Insert 10
- bst.insert(5) // Insert 5
- bst.insert(15) // Insert 15
- bst.insert(3) // Insert 3
- bst.delete(10) // Delete 10, new root becomes 5
- bst.preorderTraversal() // Returns [5, 3, 15]
Constraints
- -10^9 ≤ val ≤ 10^9
- At most 10^4 calls will be made to insert, delete, search, inorderTraversal, and preorderTraversal.
- Each val is unique.
- Time Complexity: O(h) for insert, delete, and search operations, where h is the height of the tree
- Space Complexity: O(n) for the tree storage, O(h) for recursive operations
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Create a TreeNode class to represent each node in the BST.
- For insertion, traverse the tree to find the correct position based on BST properties.
- For deletion, handle three cases: node with no children, node with one child, and node with two children.
- Use recursion for traversal operations.
- When deleting a node with two children, find the inorder successor (smallest node in right subtree).