What is a Binary Tree and a BST?
Solution and explanation
Binary tree
A tree is a hierarchical data structure of nodes connected by edges, with one root and no cycles. In a binary tree, every node has at most two children: left and right.
1 <- root (level 0)
/ \
2 3 <- level 1
/ \ \
4 5 6 <- leaves (no children)
Terminology
- Root: the top node. Leaf: a node with no children.
- Parent/child/sibling relationships.
- Depth of a node: edges from the root to it. Height of the tree: edges on the longest root-to-leaf path.
- Subtree: a node and all its descendants.
Node structure
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
// Building the tree above
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
Types of binary trees
- Full: every node has 0 or 2 children.
- Complete: all levels full except possibly the last, filled from the left (heaps).
- Perfect: all internal nodes have 2 children and all leaves are at the same level (2^(h+1) − 1 nodes).
- Balanced: heights of left and right subtrees differ by at most 1 everywhere (AVL, red-black trees), keeping height O(log n).
- Degenerate/skewed: each node has one child – effectively a linked list, height O(n).
Binary search tree (BST)
A BST is a binary tree where, for every node, all values in the left subtree are smaller and all values in the right subtree are larger. This ordering makes searching like binary search.
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
static TreeNode search(TreeNode root, int key) {
while (root != null && root.val != key) {
root = key < root.val ? root.left : root.right;
}
return root;
}
Complexity
- BST search/insert/delete: O(h) – O(log n) when balanced, O(n) when skewed (e.g. inserting sorted data).
- Traversals visit every node: O(n).
- Self-balancing trees (AVL, red-black – used by Java's TreeMap) guarantee O(log n).
Applications
- File systems and folder hierarchies, the HTML DOM, organisation charts.
- BSTs / TreeMap: ordered maps, range queries, leaderboards.
- Database indexes use B-trees and B+ trees (wide, shallow trees).
- Expression trees in compilers, decision trees in machine learning, tries for autocomplete.
Note: an in-order traversal of a BST produces its values in sorted order – the basis of many BST problems.
