Loading...
Binary trees and search operations
Section 1 of 4
A binary tree is a tree data structure where each node has at most two children, typically referred to as the left child and right child. This simple constraint makes binary trees incredibly versatile and efficient for many operations.
A Binary Search Tree is a binary tree with a special ordering property: for every node, all values in the left subtree are smaller, and all values in the right subtree are larger than the node's value.
function insert(root, value) {
if (!root) return new Node(value);
if (value < root.val) {
root.left = insert(root.left, value);
} else if (value > root.val) {
root.right = insert(root.right, value);
}
return root;
}The performance of BST operations depends heavily on the tree's balance. An unbalanced tree can degrade to O(n) performance, essentially becoming a linked list.
| Tree Type | Search | Insert | Delete |
|---|---|---|---|
| Balanced BST | O(log n) | O(log n) | O(log n) |
| Unbalanced BST | O(n) | O(n) | O(n) |
| AVL Tree | O(log n) | O(log n) | O(log n) |