Tutorialspoint
Problem
Solution
Submissions

Binary Search Tree

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to implement a Binary Search Tree (BST) with basic operations including insertion, search, and in-order traversal. A Binary Search Tree is a tree data structure where each node has at most two children, and for each node, all values in the left subtree are less than the node's value, and all values in the right subtree are greater than the node's value.

Example 1
  • Input: Insert values [5, 3, 7, 2, 4, 6, 8] and search for 4
  • Output: true
  • Explanation:
    Insert 5 as root node, insert 3 to the left of 5, 7 to the right of 5, insert 2 to the left of 3, 4 to the right of 3, insert 6 to the left of 7, 8 to the right of 7. Search for 4: Start at root 5, go left to 3, go right to 4, found!
Example 2
  • Input: Insert values [10, 5, 15, 3, 7] and search for 12
  • Output: false
  • Explanation: Insert 10 as root node, insert 5 to the left of 10, 15 to the right of 10, insert 3 to the left of 5, 7 to the right of 5. Search for 12: Start at root 10, go right to 15, go left (no node exists). Value 12 not found in the BST.
Constraints
  • 1 ≤ number of nodes ≤ 1000
  • -1000 ≤ node values ≤ 1000
  • All values inserted are unique
  • Time Complexity for insertion: O(log n) average, O(n) worst case
  • Space Complexity: O(n) for storage
AlgorithmsTreeCapgeminiSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create a TreeNode class to represent each node with value, left, and right properties
  • Create a BST class with methods for insert, search, and inOrderTraversal
  • For insertion, compare the value with current node and recursively insert in left or right subtree
  • For search, compare the target value with current node and traverse accordingly
  • Use recursive approach for cleaner implementation
  • Handle edge cases like empty tree and duplicate values

Steps to solve by this approach:

 Step 1: Create TreeNode class with value, left, and right properties

 Step 2: Create BST class with root property initialized to null
 Step 3: Implement insert method that handles empty tree case and calls recursive helper
 Step 4: Implement recursive insertion helper that compares values and inserts in appropriate subtree
 Step 5: Implement search method that calls recursive search helper
 Step 6: Implement recursive search helper that compares values and traverses accordingly
 Step 7: Implement in-order traversal for sorted output using recursive helper

Submitted Code :