Step 2 of 6
33% CompleteInsert Operation in Binary Search Trees
Learn how to add new nodes to a binary search tree
Understanding the Insert Operation
Insertion in a binary search tree (BST) involves adding a new node while maintaining the BST property: for each node, all elements in its left subtree are less than the node's value, and all elements in its right subtree are greater than the node's value.
Insertion Algorithm
The insertion algorithm follows these steps:
- If the tree is empty, create a new node and make it the root.
- Otherwise, compare the new value with the current node's value.
- If the new value is less than the current node's value, recursively insert into the left subtree. If the left child is null, create a new node and make it the left child.
- If the new value is greater than the current node's value, recursively insert into the right subtree. If the right child is null, create a new node and make it the right child.
- If the value already exists in the tree, you can either update it or ignore the insertion.
Implementation
Here's how we implement the insert operation in TypeScript:
class TreeNode {value: number;left: TreeNode | null;right: TreeNode | null;constructor(value: number) {this.value = value;this.left = null;this.right = null;}}class BinarySearchTree {root: TreeNode | null;constructor() {this.root = null;}insert(value: number): void {const newNode = new TreeNode(value);if (this.root === null) {this.root = newNode;return;}const insertNode = (node: TreeNode, newNode: TreeNode): void => {if (newNode.value < node.value) {if (node.left === null) {node.left = newNode;} else {insertNode(node.left, newNode);}} else if (newNode.value > node.value) {if (node.right === null) {node.right = newNode;} else {insertNode(node.right, newNode);}}};insertNode(this.root, newNode);}}
Example
Let's see how insertion works with an example:
- Start with an empty tree and insert 10. This becomes the root.
- Insert 5. Since 5 < 10, it becomes the left child of 10.
- Insert 15. Since 15 > 10, it becomes the right child of 10.
- Insert 3. Since 3 < 10 and 3 < 5, it becomes the left child of 5.
- Insert 7. Since 7 < 10 but 7 > 5, it becomes the right child of 5.
- Insert 12. Since 12 > 10 but 12 < 15, it becomes the left child of 15.
- Insert 18. Since 18 > 10 and 18 > 15, it becomes the right child of 15.
The resulting tree would look like:
10 / \ 5 15 / \ / \ 3 7 12 18
Time and Space Complexity
Time Complexity: O(h) where h is the height of the tree. In a balanced BST, this is O(log n), but in the worst case (a skewed tree), it can be O(n).
Space Complexity: O(h) for the recursive call stack, where h is the height of the tree.
Next Steps
Now that you understand how to insert nodes into a binary search tree, let's move on to the search operation, which allows us to find specific values within the tree structure.