Binary Search Tree - Problem

Implement a Binary Search Tree (BST) with the following operations:

  • insert(val): Insert a value into the BST
  • search(val): Search for a value in the BST (return true/false)
  • delete(val): Delete a value from the BST
  • inorder(): 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
INPUT OPERATIONSBST ALGORITHMFINAL RESULTS["insert", 10]["insert", 5]["insert", 15]["search", 10]["inorder"]1Build Tree StructureInsert nodes maintaining BST property2Search OperationsUse BST property for O(log n) search3Tree TraversalsRecursive DFS with different orders10515Left < Root < Rightnullnullnulltrue[5, 10, 15]Key Insight:Binary Search Tree structure with recursive operations enables O(log n) average performancefor insert, search, delete, and traversal operations instead of O(n) linear time.TutorialsPoint - Binary Search Tree | Proper BST Implementation
Asked in
Google 35 Amazon 42 Microsoft 28 Facebook 31
89.0K Views
High Frequency
~35 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen