Chapter 09
Binary Trees & BST
4 topics · 3 sections · beginner-friendly study notes · Updated
A binary tree has at most two children per node.
DFS (pre/in/post-order) and BFS (level order) traverse it in O(n); a BST keeps left < node < right so search, insert and delete cost O(h), which is O(log n) when balanced and O(n) when skewed.
Trees are the most common non-linear structure in interviews and GATE (traversal outputs, node counts, BST insertion sequences).
File systems, expression trees, database indexes (B-trees), autocomplete (tries), decision trees.
Binary Tree Terminology
A binary tree is a rooted tree where each node has at most two children (left, right). Depth of a node = edges from root; height of a node = edges to the deepest leaf below it; height of tree = height of root. Level of root is 0 (or 1 by some textbooks).
In short: A hierarchy where every node has up to two children.

Think about it
GATE repeatedly asks node/leaf/height relations and number of tree shapes.
Maximum nodes at level l = 2^l; maximum nodes in a tree of height h = 2^(h+1) - 1; minimum nodes = h + 1 (skewed).
With n nodes: minimum height = floor(log2 n), maximum height = n - 1.
Leaves = (nodes with two children) + 1, so n0 = n2 + 1.
Full (strict) binary tree: every node has 0 or 2 children.
Complete: all levels full except possibly the last, filled left to right (heap shape; array storage with children 2i+1, 2i+2).
Perfect: all leaves same level, 2^(h+1)-1 nodes.
Balanced (AVL): height difference of subtrees <= 1 at every node, height O(log n).
Degenerate (skewed): each node has one child, behaves like a linked list.
Number of distinct binary tree shapes with n nodes is the Catalan number C(2n,n)/(n+1); labeled BSTs with n distinct keys: the same Catalan number.
Edges = n - 1.
Height of an empty tree is -1 (edges convention) or 0 (nodes convention) - state the convention.
Key points
- Leaf: Node with no children.
- Depth vs height: Depth counts down from root; height counts down to leaves.
- Complete tree: Levels full except last, left-aligned.
- Skewed tree: Every node has exactly one child.
- Array representation (0-indexed): parent (i-1)//2, left 2i+1, right 2i+2. 1-indexed: parent i//2, children 2i, 2i+1.
- A tree with n nodes has n-1 edges; n0 = n2 + 1 for binary trees.
Example
CodeHeight, size, balance check:
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def height(root): # edges convention: empty = -1
if not root: return -1
return 1 + max(height(root.left), height(root.right))
def count_nodes(root):
return 0 if not root else 1 + count_nodes(root.left) + count_nodes(root.right)
def is_balanced(root): # O(n)
def h(n):
if not n: return 0
l, r = h(n.left), h(n.right)
if l < 0 or r < 0 or abs(l - r) > 1: return -1
return 1 + max(l, r)
return h(root) >= 0Tree Traversals (DFS vs BFS)
DFS goes deep first: preorder (root, left, right), inorder (left, root, right), postorder (left, right, root). BFS (level order) visits nodes level by level using a queue. All take O(n) time; DFS uses O(h) space, BFS uses O(w) where w is the maximum width.
In short: DFS dives down one branch before backtracking; BFS sweeps across each level.
Think about it
Traversal outputs and reconstruction are among the most reliable GATE question types.
Preorder copies a tree and serializes it; inorder of a BST yields sorted keys; postorder deletes a tree and evaluates expression trees (children before operator).
Iterative inorder uses a stack and pushes left spine; iterative preorder pushes right then left; postorder iterative uses two stacks or last-visited tracking.
Morris traversal gives O(1) extra space using threaded links.
BFS space can be O(n/2) for a perfect tree (last level), DFS O(log n) there but O(n) for a skewed tree.
Reconstruction: inorder + preorder (or inorder + postorder) uniquely determines a tree; preorder + postorder does not in general (unless full).
Preorder + inorder: first preorder element is the root; locate it in inorder to split left and right sizes; use a hash map for O(n).
Number of distinct trees with a given preorder sequence of n nodes is Catalan.
Level-order variants: zigzag, right-side view (last node of each level), per-level averages.
Postorder of BST insertion order check: preorder of a BST can be validated with a stack in O(n).
Key points
- Preorder: Root, left, right.
- Inorder: Left, root, right (sorted for BST).
- Postorder: Left, right, root.
- Level order: BFS by levels with a queue.
Example
CodeAll traversals and reconstruction:
from collections import deque
def inorder(r): # iterative, O(h) stack
res, st, cur = [], [], r
while cur or st:
while cur:
st.append(cur); cur = cur.left
cur = st.pop(); res.append(cur.val); cur = cur.right
return res
def preorder(r):
if not r: return []
res, st = [], [r]
while st:
n = st.pop(); res.append(n.val)
if n.right: st.append(n.right)
if n.left: st.append(n.left)
return res
def postorder(r): # reverse of (root, right, left)
if not r: return []
res, st = [], [r]
while st:
n = st.pop(); res.append(n.val)
if n.left: st.append(n.left)
if n.right: st.append(n.right)
return res[::-1]
def level_order(r):
if not r: return []
res, q = [], deque([r])
while q:
level = []
for _ in range(len(q)):
n = q.popleft(); level.append(n.val)
if n.left: q.append(n.left)
if n.right: q.append(n.right)
res.append(level)
return res
def build(pre, ino): # preorder + inorder, O(n)
idx = {v: i for i, v in enumerate(ino)}
it = iter(pre)
def go(lo, hi):
if lo > hi: return None
root = TreeNode(next(it))
m = idx[root.val]
root.left = go(lo, m - 1)
root.right = go(m + 1, hi)
return root
return go(0, len(ino) - 1)BST Search, Insert & Delete
A binary search tree satisfies: for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger (distinct keys). Search, insert and delete follow one root-to-leaf path: O(h).
In short: Go left if the key is smaller, right if larger; new keys always become leaves.
Think about it
Delete with two children and the validity check are the most common interview and GATE tricks.
Height h ranges from log2(n+1)-1 (balanced) to n-1 (inserted in sorted order).
Insert: search for the null position and attach; duplicates are rejected or counted.
Delete has three cases: (1) leaf: remove; (2) one child: replace the node by its child; (3) two children: replace the key by its inorder successor (minimum of right subtree) or predecessor, then delete that node (which has at most one child).
Inorder traversal yields sorted order, so a BST is valid iff inorder is strictly increasing; the common wrong validation checks only parent-child pairs - correct validation passes (low, high) bounds.
Minimum = leftmost node, maximum = rightmost.
Successor of node with right child = min of right subtree; otherwise the lowest ancestor whose left subtree contains the node.
Different insertion orders give different shapes for the same key set (n!
orders, Catalan shapes).
Building from a sorted array in the middle-first order gives a height-balanced BST in O(n).
Self-balancing trees (AVL: |balance| <= 1, red-black) guarantee O(log n).
k-th smallest: inorder with counter, or augment nodes with subtree sizes for O(h).
Key points
- Inorder successor: Next larger key; min of right subtree or lowest ancestor for which node is in left subtree.
- BST property: left < node < right, applied to entire subtrees.
- AVL tree: BST with |
height(left)-height(right)|<=1 at every node. - Search/insert/delete: average
O(log n)for random insertions, worstO(n)for sorted insertions. - Inserting 10,20,30,40 into an empty BST yields a right-skewed chain of height 3.
Example
CodeBST operations and validation:
def search(root, key):
while root and root.val != key:
root = root.left if key < root.val else root.right
return root
def insert(root, key):
if not root: return TreeNode(key)
if key < root.val: root.left = insert(root.left, key)
elif key > root.val: root.right = insert(root.right, key)
return root
def delete(root, key):
if not root: return None
if key < root.val: root.left = delete(root.left, key)
elif key > root.val: root.right = delete(root.right, key)
else:
if not root.left: return root.right
if not root.right: return root.left
succ = root.right
while succ.left: succ = succ.left # inorder successor
root.val = succ.val
root.right = delete(root.right, succ.val)
return root
def is_valid_bst(root, lo=float('-inf'), hi=float('inf')):
if not root: return True
if not (lo < root.val < hi): return False
return (is_valid_bst(root.left, lo, root.val) and
is_valid_bst(root.right, root.val, hi))
def sorted_to_bst(a, lo=0, hi=None):
if hi is None: hi = len(a) - 1
if lo > hi: return None
m = (lo + hi) // 2
return TreeNode(a[m], sorted_to_bst(a, lo, m - 1), sorted_to_bst(a, m + 1, hi))Lowest Common Ancestor (LCA)
The LCA of nodes p and q is the deepest node that has both p and q as descendants (a node counts as its own descendant). In a BST it is found in O(h) using key comparison; in a general binary tree it needs an O(n) recursive search.
In short: The lowest shared boss of two nodes in the tree.
Think about it
Frequent interview question with two distinct solutions (BST vs general tree) and a cornerstone for tree distance queries.
BST: starting at the root, if both keys < node go left, if both > node go right, otherwise the current node is the LCA (split point or one equals node).
Iterative O(h) time and O(1) space.
General binary tree: recurse; if the current node is None, p or q return it; collect left and right results; if both are non-null the current node is the LCA, else return the non-null one.
This assumes both nodes exist; if one may be missing, count found nodes.
With parent pointers: climb with two pointers like intersecting linked lists, or store ancestors in a set.
Alternative: store root-to-node paths and find the last common element, O(n) time and space.
Many-query LCA: binary lifting (O(n log n) preprocessing, O(log n) per query) or Euler tour + RMQ (O(1) query).
Distance between two nodes = depth(p) + depth(q) - 2*depth(LCA).
Diameter, path sum and similar problems use the same postorder combine pattern.
Key points
Example
CodeLCA and diameter:
def lca_bst(root, p, q):
while root:
if p < root.val and q < root.val: root = root.left
elif p > root.val and q > root.val: root = root.right
else: return root
return None
def lca(root, p, q): # general binary tree, O(n)
if not root or root.val == p or root.val == q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left and right: return root
return left or right
def diameter(root): # edges on the longest path
best = 0
def h(n):
nonlocal best
if not n: return 0
l, r = h(n.left), h(n.right)
best = max(best, l + r)
return 1 + max(l, r)
h(root)
return bestSolved examples
A binary tree has 15 nodes with 8 leaves. How many nodes have two children?
n2
Formula Applied:—Approach note: Valid for every binary tree regardless of n1.
Preorder = A B D E C F, Inorder = D B E A F C. Give postorder.
Postorder
Formula Applied:—Approach note: Postorder = left, right, root recursively.
Insert 50, 30, 70, 20, 40, 60, 80 then delete 50. What is the new root and shape?
Result
Formula Applied:—Approach note: Using the predecessor (40) instead is equally valid.
Insert 7, 3, 9, 1, 5 into an empty BST. What is the inorder traversal?
Inorder sequence
Formula Applied:—Approach note: Inorder of a BST always sorts the keys.
Real-world applications
Using Binary Trees & BST in real projects
File systems, expression trees, database indexes (B-trees), autocomplete (tries), decision trees.
Common mistakes
❌ Myth: A BST is valid if each node is greater than its left child and smaller than its right child.
Why this is wrong: The property applies to whole subtrees; a deeper left descendant may exceed an ancestor.
✅ Verified Truth: Validate with (low, high) bounds or check strictly increasing inorder.
⚠️ Exam Tip: Counter-example: root 10, left 5, whose right child is 15.
❌ Myth: BST operations are always O(log n).
Why this is wrong: Sorted insertions create a skewed tree with height n-1.
✅ Verified Truth: O(h): log n balanced, n worst case; use AVL/red-black for guarantees.
⚠️ Exam Tip: State both average and worst case.
❌ Myth: Preorder and postorder together uniquely define a binary tree.
Why this is wrong: A single-child node can be left or right child with identical sequences.
✅ Verified Truth: Inorder + (pre or post) is unique; pre + post is unique only for full trees.
⚠️ Exam Tip: Common GATE trap.
Revision notes
A binary tree has at most two children per node. DFS (pre/in/post-order) and BFS (level order) traverse it in O(n); a BST keeps left < node < right so search, insert and delete cost O(h), which is O(log n) when balanced and O(n) when skewed.
High-Yield Quick Revision Points
- n0 = n2 + 1; max nodes 2^(h+1)-1; min height floor(log2 n)
- Pre: root L R; In: L root R; Post: L R root; BFS queue
- In + pre/post reconstructs uniquely; pre + post does not
- BST ops O(h); delete 2 children -> inorder successor; validate with bounds
- LCA: BST by comparison O(h); general tree recursion O(n); dist = d(p)+d(q)-2d(lca)
Practice questions
Maximum nodes in a binary tree of height h (root height 0)?
Inorder traversal of a BST gives:
Binary tree with 20 leaves has how many nodes of degree 2?
Worst-case search time in BST of n nodes:
Number of different BSTs with 3 distinct keys:
BFS space on perfect tree with n nodes: