ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Binary Search Tree Insertion

JavaScript

Goal -- WPM

Ready
Exercise Algorithm Area
1class TreeNode {
2constructor(val) {
3this.val = val;
4this.left = this.right = null;
5}
6}
7
8function insertIntoBST(root, val) {
9// If the tree is empty, create a new node and return it as the root
10if (root === null) {
11return new TreeNode(val);
12}
13
14// Traverse the tree to find the correct insertion point
15let currentNode = root;
16while (true) {
17if (val < currentNode.val) {
18// Go left
19if (currentNode.left === null) {
20currentNode.left = new TreeNode(val);
21break; // Node inserted
22}
23currentNode = currentNode.left;
24} else {
25// Go right (handles duplicates by placing them to the right)
26if (currentNode.right === null) {
27currentNode.right = new TreeNode(val);
28break; // Node inserted
29}
30currentNode = currentNode.right;
31}
32}
33
34return root; // Return the original root
35}
Algorithm description viewbox

Binary Search Tree Insertion

Algorithm description:

This function inserts a new value into a Binary Search Tree (BST). A BST is a data structure where each node has at most two children, and for any given node, all values in its left subtree are less than the node's value, and all values in its right subtree are greater than the node's value. This property allows for efficient searching, insertion, and deletion operations.

Algorithm explanation:

The `insertIntoBST` function takes the root of a BST and a value to insert. If the tree is empty (`root` is `null`), it creates a new `TreeNode` with the given value and returns it as the new root. Otherwise, it starts from the root and iteratively traverses the tree. If the value to be inserted is less than the current node's value, it attempts to go left. If the left child is `null`, the new node is inserted there. If the value is greater than or equal to the current node's value, it attempts to go right. If the right child is `null`, the new node is inserted there. This process continues until the node is inserted. The time complexity for insertion is O(h), where h is the height of the tree, which is O(log n) for a balanced BST and O(n) in the worst case (a skewed tree). The space complexity is O(1) for the iterative approach.

Pseudocode:

class TreeNode:
  value
  left child
  right child

function insertIntoBST(root, value):
  if root is null:
    return new TreeNode(value)

  current = root
  while true:
    if value < current.value:
      if current.left is null:
        current.left = new TreeNode(value)
        break
      else:
        current = current.left
    else:
      if current.right is null:
        current.right = new TreeNode(value)
        break
      else:
        current = current.right

  return root