Insertion
Compare the new value with each visited node. Move left for a smaller value and right for a larger value until an empty child position is found.
A Binary Search Tree (BST) is a binary tree in which every value in a node's left subtree is smaller and every value in its right subtree is larger. This ordering supports efficient search, insertion, and deletion when the tree remains reasonably balanced.
Example tree loaded. Choose an operation.
search(node, value):
if node is null:
return not found
if value == node.value:
return node
if value < node.value:
return search(node.left, value)
return search(node.right, value)Compare the new value with each visited node. Move left for a smaller value and right for a larger value until an empty child position is found.
A leaf is removed directly. A node with one child is replaced by that child. A node with two children is replaced by its inorder successor.
Inorder visits Left–Root–Right, preorder Root–Left–Right, postorder Left–Right–Root, and level order visits breadth by breadth.
A balanced BST has logarithmic height. Sorted insertion can create a skewed tree whose operations degrade to O(n).
| Operation | Balanced | Worst case |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| Traversal | O(n) | O(n) |
| Space | O(n) | O(n) |