Knowledge / Computer Science and Engineering / Trees and binary search trees

Trees and binary search trees

Computer Science and Engineering (B.E./B.Tech) · Data structures · free study notes for exams, placements and interviews

In short

A tree is a hierarchical, acyclic data structure of nodes in which every node except the root has exactly one parent; a binary tree restricts each node to at most two children, and a binary search tree (BST) adds the ordering rule that everything in the left subtree is smaller and everything in the right subtree is larger than the node's key. This ordering gives search, insert and delete in O(h) time, which is O(log n) when the tree is shaped well and O(n) when it degenerates into a list. Trees are compulsory in every Indian CS syllabus (AICTE model curriculum, UGC CBCS data structures course) and appear in GATE CS every year as traversals, height/node counting, Catalan counting and BST operations. In placements they are the backbone of tree rounds at TCS NQT, Infosys, Wipro, Accenture and of the hard rounds at Amazon, Microsoft, Google, Flipkart, Zoho, Adobe and Oracle India.

Explained

Terminology and basic properties

Types of binary trees

Representation in memory

Traversals

Depth-first traversals, each O(n) time; auxiliary space O(h) for the recursion stack (O(n) worst case, O(log n) balanced):

  1. Inorder (LNR): left, node, right. On a BST this outputs keys in ascending order — the most used property in exams.
  2. Preorder (NLR): node, left, right. Used to copy/serialise a tree; prefix form of an expression.
  3. Postorder (LRN): left, right, node. Used to delete/free a tree, compute heights and sizes bottom-up; postfix expression.
  4. Level order (BFS): level by level, using a queue; O(n) time, O(w) space where w is the maximum width.
  5. Iterative versions: inorder and preorder with an explicit stack; postorder with two stacks or one stack plus a "last visited" pointer.
  6. Morris traversal: inorder in O(n) time and O(1) extra space by temporarily threading the rightmost node of the left subtree back to the current node, then undoing it.
  7. Reconstruction: inorder + preorder, or inorder + postorder, determine a binary tree uniquely (keys distinct). Preorder + postorder do not — they cannot tell a single left child from a single right child, but they do determine a full binary tree uniquely. For a BST, preorder alone (or postorder alone, or level order alone) is enough, because sorting it gives the inorder.

BST operations

Complexity, shape and counting

/* Iterative BST search and insert */
node* search(node *r, int k){
    while (r && r->data != k) r = (k < r->data) ? r->left : r->right;
    return r;                      /* NULL if absent */
}
node* insert(node *r, int k){      /* recursive; returns new subtree root */
    if (!r) return newnode(k);
    if (k < r->data) r->left  = insert(r->left,  k);
    else if (k > r->data) r->right = insert(r->right, k);
    return r;                      /* duplicate ignored */
}
int height(node *r){               /* edges; empty tree = -1 */
    if (!r) return -1;
    int l = height(r->left), rt = height(r->right);
    return 1 + (l > rt ? l : rt);
}
int isBST(node *r, int lo, int hi){
    if (!r) return 1;
    if (r->data <= lo || r->data >= hi) return 0;
    return isBST(r->left, lo, r->data) && isBST(r->right, r->data, hi);
}

Key points

Formulas and examples

Maximum nodes at level l (root at level 0) = 2l
Maximum nodes in a binary tree of height h = 2h+1 − 1 (edge convention)
Minimum nodes in a binary tree of height h = h + 1
Minimum height for n nodes = ⌊log₂ n⌋; maximum height = n − 1
Perfect binary tree: n = 2h+1 − 1, leaves = 2h = (n + 1)/2, h = log₂(n + 1) − 1
Leaves and two-child nodes: n₀ = n₂ + 1; total n = n₀ + n₁ + n₂
NULL pointers in a binary tree with n nodes = n + 1
Array indices (0-based): left = 2i + 1, right = 2i + 2, parent = ⌊(i − 1)/2⌋
Number of distinct BSTs on n distinct keys = Catalan Cₙ = (1/(n+1)) × C(2n, n) = (2n)! / (n! (n+1)!)
Labelled binary trees on n nodes = Cₙ × n!
Average comparisons for a successful search = (internal path length / n) + 1
BST operation cost = O(h); h = Θ(log n) balanced, Θ(n) skewed; random insertion gives an expected search cost ≈ 1.39 log₂ n comparisons

Example 1 — Build a BST and traverse it. Insert 50, 30, 70, 20, 40, 60, 80 in that order.

Example 2 — Deletion, all three cases, on the tree of Example 1.

Example 3 — Reconstruct a tree from two traversals. Preorder = A B D E C F, Inorder = D B E A C F.

Example 4 — Counting. How many distinct BSTs can be made with the keys {1, 2, 3, 4}?

Example 5 — Counting nodes and height. A binary tree has 20 nodes of degree 2 and 10 nodes of degree 1.

OperationBST (balanced)BST (skewed)Sorted arrayHash table
SearchO(log n)O(n)O(log n)O(1) average
Insert / deleteO(log n)O(n)O(n)O(1) average
Minimum / maximumO(log n)O(n)O(1)O(n)
Successor / floor / ceilingO(log n)O(n)O(log n)O(n)
Keys in sorted orderO(n) inorderO(n)O(n)O(n log n)
Extra space2n child pointers2n child pointersnoneload-factor slack
TraversalOrderTypical use
InorderL N RSorted output from a BST; infix expression
PreorderN L RCopy/serialise a tree; prefix expression
PostorderL R NFree a tree; compute height/size; postfix expression
Level orderBFS by levelWidth, shortest depth, printing by level

Where it is used

Interview questions

Common mistakes

Related topics

Balanced trees: AVL, red-black and B-trees · Heaps and priority queues · Hashing and hash tables · Tries and string data structures · Graphs and their representation · Recursion and divide-and-conquer

Open in the Knowledge reader →Find jobs →