Binary Search Tree - Problem
Implement a Binary Search Tree (BST) with the following operations:
insert(val): Insert a value into the BSTsearch(val): Search for a value in the BST (return true/false)delete(val): Delete a value from the BSTinorder(): Return in-order traversal (left-root-right)preorder(): Return pre-order traversal (root-left-right)postorder(): Return post-order traversal (left-right-root)
You will receive a list of operations to perform on an initially empty BST. Each operation is represented as [operation, value] where operation is one of the strings above and value is the integer to operate on (omitted for traversals).
Return an array containing the results of each operation. For insert and delete, return null. For search, return boolean. For traversals, return the array of values.
Input & Output
Example 1 — Basic BST Operations
$
Input:
operations = [["insert", 10], ["insert", 5], ["insert", 15], ["search", 10], ["inorder"]]
›
Output:
[null, null, null, true, [5, 10, 15]]
💡 Note:
Insert 10 (root), insert 5 (left of 10), insert 15 (right of 10), search for 10 (found), inorder traversal gives sorted order [5, 10, 15]
Example 2 — Search and Traversal
$
Input:
operations = [["insert", 8], ["insert", 3], ["insert", 12], ["search", 7], ["preorder"]]
›
Output:
[null, null, null, false, [8, 3, 12]]
💡 Note:
Build BST with 8 as root, 3 as left child, 12 as right child. Search for 7 returns false (not found). Preorder traversal visits root first: [8, 3, 12]
Example 3 — Delete Operation
$
Input:
operations = [["insert", 20], ["insert", 10], ["insert", 30], ["delete", 20], ["inorder"]]
›
Output:
[null, null, null, null, [10, 30]]
💡 Note:
Insert 20, 10, 30. Delete root node 20 (replaced by successor 30). Final inorder traversal shows remaining nodes: [10, 30]
Constraints
- 1 ≤ operations.length ≤ 1000
- -104 ≤ val ≤ 104
- All values are unique when inserted
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code