Notes
All notes

Trees and Binary Search Trees (DSA Core #5)

A tree is a graph with no cycles and one root. That one restriction gives you recursion, ordered traversal, and \(O(\log n)\) search when the tree is balanced. Most tree problems are one of four things: traverse, search, compute something bottom-up, or rebuild the tree from a traversal.

Terminology and the properties worth remembering

A tree with \(n\) nodes has exactly \(n-1\) edges. That is the edge count of any connected acyclic graph, and it is why “count edges” is a cycle check in disguise.

For a binary tree, the number of nodes at depth \(d\) is at most \(2^d\), so

\[ n \le 2^{h+1} - 1 \quad\Longleftrightarrow\quad h \ge \lceil \log_2(n+1) \rceil - 1 \]

A balanced tree has height \(O(\log n)\). A path-shaped tree has height \(n-1\), and every recursive traversal on it uses \(O(n)\) stack. That is the difference between a working solution and a stack overflow on a \(10^5\)-node chain.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.65cm, font=\small\bfseries},
  a/.style={->, thick}]
  \node[n, fill=blue!15] (r) at (0,0) {8};
  \node[n] (l) at (-1.5,-1.0) {3};
  \node[n] (rr) at (1.5,-1.0) {10};
  \node[n] (ll) at (-2.3,-2.0) {1};
  \node[n] (lr) at (-0.7,-2.0) {6};
  \node[n] (rl) at (0.7,-2.0) {9};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
  \draw[a] (rr) -- (rl);
  \node[font=\scriptsize, anchor=west] at (2.2,0) {depth 0, height 2};
  \node[font=\scriptsize, anchor=west] at (2.2,-1.0) {depth 1};
  \node[font=\scriptsize, anchor=west] at (2.2,-2.0) {depth 2, leaves};
\end{tikzpicture}
QQuestionA binary tree has 15 nodes. What are the minimum and maximum possible

heights?

ASolution

Minimum 3 (a perfect tree of height 3 has \(2^4-1 = 15\) nodes). Maximum 14, a single chain.

Shapes: full, complete, perfect

Shape Definition Node count
Full every node has 0 or 2 children no fixed count
Complete all levels filled except the last, which fills left to right between \(2^h\) and \(2^{h+1}-1\)
Perfect full and all leaves at the same depth exactly \(2^{h+1}-1\)

Complete matters because a complete binary tree fits an array with no pointers: the children of index i are 2i+1 and 2i+2, and the parent is (i-1)/2. That is the heap layout (Ch. 11 of the DSA course, and below).

vector<int> heap = {10, 7, 9, 3, 5};
// children of index 1 (value 7) sit at 2*1+1 = 3 and 2*1+2 = 4: values 3 and 5

Perfect trees are the recursion base cases: 2^h - 1 nodes means every internal node has two children and every leaf is at the bottom, so a check for perfect is “count nodes == 2^height - 1” or a recursive isPerfect(l) && isPerfect(r) && height(l) == height(r).

QQuestionWhy does a complete tree of \(n\) nodes have height \(\lfloor \log_2 n

\rfloor\)?

ASolution

Every level except the last is full, so the node count is at least \(2^h\) and at most \(2^{h+1}-1\), giving \(h = \lfloor \log_2 n \rfloor\).

The four traversals

Preorder (node, left, right) copies a tree. Inorder (left, node, right) reads a BST in sorted order. Postorder (left, right, node) computes bottom-up — subtree sizes, heights, deletions. Level order goes breadth-first.

void preorder(TreeNode* n, vector<int>& out) {
    if (!n) return;
    out.push_back(n->val);
    preorder(n->left, out);
    preorder(n->right, out);
}
void inorder(TreeNode* n, vector<int>& out) {
    if (!n) return;
    inorder(n->left, out);
    out.push_back(n->val);
    inorder(n->right, out);
}

Iterative versions matter when the tree is deep. Preorder is a stack with the right child pushed first so the left is processed first:

vector<int> preorderIt(TreeNode* root) {
    vector<int> out;
    vector<TreeNode*> st;
    if (root) st.push_back(root);
    while (!st.empty()) {
        TreeNode* n = st.back(); st.pop_back();
        out.push_back(n->val);
        if (n->right) st.push_back(n->right);
        if (n->left) st.push_back(n->left);
    }
    return out;
}

Inorder iteratively is the one to memorize — it is the template for BST iterator problems:

vector<int> inorderIt(TreeNode* root) {
    vector<int> out;
    vector<TreeNode*> st;
    TreeNode* cur = root;
    while (cur || !st.empty()) {
        while (cur) { st.push_back(cur); cur = cur->left; }
        cur = st.back(); st.pop_back();
        out.push_back(cur->val);
        cur = cur->right;
    }
    return out;
}

Postorder is preorder with the children pushed in the opposite order, then reversed:

vector<int> postorderIt(TreeNode* root) {
    vector<int> out;
    vector<TreeNode*> st;
    if (root) st.push_back(root);
    while (!st.empty()) {
        TreeNode* n = st.back(); st.pop_back();
        out.push_back(n->val);
        if (n->left) st.push_back(n->left);
        if (n->right) st.push_back(n->right);
    }
    reverse(out.begin(), out.end());
    return out;
}

Level order needs a queue and a loop over the current level size to keep levels separate:

vector<vector<int>> levelOrder(TreeNode* root) {
    vector<vector<int>> out;
    if (!root) return out;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        int sz = q.size();
        vector<int> level;
        for (int i = 0; i < sz; ++i) {
            TreeNode* n = q.front(); q.pop();
            level.push_back(n->val);
            if (n->left) q.push(n->left);
            if (n->right) q.push(n->right);
        }
        out.push_back(level);
    }
    return out;
}

int sz = q.size() before the inner loop is required; using q.size() directly in the condition processes the next level’s nodes too.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\scriptsize\bfseries}]
  \node[n, fill=orange!30] (r) at (0,0) {1};
  \node[n, fill=blue!15] (l) at (-1.2,-0.9) {2};
  \node[n, fill=blue!15] (rr) at (1.2,-0.9) {3};
  \node[n, fill=green!20] (ll) at (-1.9,-1.8) {4};
  \node[n, fill=green!20] (lr) at (-0.5,-1.8) {5};
  \draw[->, thick] (r) -- (l); \draw[->, thick] (r) -- (rr);
  \draw[->, thick] (l) -- (ll); \draw[->, thick] (l) -- (lr);
  \node[font=\scriptsize, anchor=west] at (2.0,0) {pre: 1 2 4 5 3};
  \node[font=\scriptsize, anchor=west] at (2.0,-0.5) {in: 4 2 5 1 3};
  \node[font=\scriptsize, anchor=west] at (2.0,-1.0) {post: 4 5 2 3 1};
  \node[font=\scriptsize, anchor=west] at (2.0,-1.5) {level: 1 | 2 3 | 4 5};
\end{tikzpicture}

Morris traversal does inorder in \(O(1)\) space by temporarily threading the tree through right pointers. It is a nice trick and almost never the expected answer in an OA; mention it, do not lead with it.

QQuestionWhich traversal would you use to delete a tree without leaking

memory?

ASolution

Postorder: children are freed before the parent, so no node is reached after its storage is released.

Height and depth

Height is a postorder computation: the answer for a node needs both children.

int height(TreeNode* n) {
    if (!n) return 0;                       // height in nodes; use -1 for edges
    return 1 + max(height(n->left), height(n->right));
}

That is \(O(n)\) but it re-walks subtrees if you call it at every node (as in a balanced check) — \(O(n^2)\) on a skewed tree. The fix is to return both pieces of information from one pass:

bool balanced(TreeNode* n, int& h) {
    if (!n) { h = 0; return true; }
    int lh, rh;
    if (!balanced(n->left, lh) || !balanced(n->right, rh)) return false;
    h = 1 + max(lh, rh);
    return abs(lh - rh) <= 1;
}

Define the convention once. Height as nodes gives height(nullptr) = 0 and a leaf has height 1. Height as edges gives 0 for a leaf. Mixing them produces off-by-one answers in diameter and depth problems.

QQuestionWhy is calling height() inside a per-node loop \(O(n^2)\) on a

chain?

ASolution

The root’s height call walks \(n\) nodes, the child’s walks \(n-1\), and so on: \(n + (n-1) + \dots + 1 = O(n^2)\). One postorder pass fixes it.

Binary search trees

A BST satisfies: every value in the left subtree is less than the node, every value in the right subtree is greater, and both subtrees are BSTs. The global version (“less than every ancestor on the right”) is the one that matters — a local check of parent-child pairs passes trees that are not BSTs.

bool isValidBST(TreeNode* n, long long lo, long long hi) {
    if (!n) return true;
    if (n->val <= lo || n->val >= hi) return false;
    return isValidBST(n->left, lo, n->val) &&
           isValidBST(n->right, n->val, hi);
}

The bounds are long long so the initial \(\pm\infty\) fit. The alternative is an inorder traversal that checks the sequence is strictly increasing, which is the same statement.

Search and insert follow one path, \(O(h)\):

TreeNode* search(TreeNode* n, int key) {
    while (n && n->val != key) n = key < n->val ? n->left : n->right;
    return n;
}
TreeNode* insert(TreeNode* n, int key) {
    if (!n) return new TreeNode(key);
    if (key < n->val) n->left = insert(n->left, key);
    else if (key > n->val) n->right = insert(n->right, key);
    return n;                      // duplicates ignored
}

Delete has three cases. No left child or no right child: splice the survivor up. Two children: copy the inorder successor’s value into the node, then delete the successor from the right subtree (the successor has no left child, so that deletion is easy).

TreeNode* remove(TreeNode* n, int key) {
    if (!n) return nullptr;
    if (key < n->val) n->left = remove(n->left, key);
    else if (key > n->val) n->right = remove(n->right, key);
    else {
        if (!n->left) { TreeNode* r = n->right; delete n; return r; }
        if (!n->right) { TreeNode* l = n->left; delete n; return l; }
        TreeNode* s = n->right;
        while (s->left) s = s->left;          // inorder successor
        n->val = s->val;
        n->right = remove(n->right, s->val);
    }
    return n;
}

All three are \(O(h)\): \(O(\log n)\) balanced, \(O(n)\) for a chain. A BST built from sorted input is a chain, which is the reason self-balancing trees exist.

QQuestionWhy is checking only left->val < node->val < right->val not enough

to validate a BST?

ASolution

It misses violations across more than one level. A node in the right subtree must be greater than every ancestor on the left, not just its parent.

Lowest common ancestor and diameter

For a BST, LCA uses the ordering directly: the first node whose value lies between p and q is the split point.

TreeNode* lcaBST(TreeNode* root, int p, int q) {
    while (root) {
        if (p < root->val && q < root->val) root = root->left;
        else if (p > root->val && q > root->val) root = root->right;
        else return root;
    }
    return nullptr;
}

For a general binary tree, recurse and return the node when both sides report a find:

TreeNode* lca(TreeNode* n, TreeNode* p, TreeNode* q) {
    if (!n || n == p || n == q) return n;
    TreeNode* l = lca(n->left, p, q);
    TreeNode* r = lca(n->right, p, q);
    if (l && r) return n;            // p and q split here
    return l ? l : r;
}

The diameter is the longest path between any two nodes, counted in edges. It does not have to pass through the root, so the answer is the maximum over all nodes of leftHeight + rightHeight.

int best = 0;
int depth(TreeNode* n) {
    if (!n) return 0;
    int l = depth(n->left), r = depth(n->right);
    best = max(best, l + r);         // path through n
    return 1 + max(l, r);            // height to parent
}

One pass, \(O(n)\): each node returns its height and updates the global best with the path through itself. The same shape solves “maximum path sum” with values (Ch. 7) by clamping negative gains to zero.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\scriptsize\bfseries},
  a/.style={->, thick}]
  \node[n, fill=orange!25] (r) at (0,0) {1};
  \node[n] (l) at (-1.2,-0.85) {2};
  \node[n] (rr) at (1.2,-0.85) {3};
  \node[n, fill=green!20] (ll) at (-1.8,-1.7) {4};
  \node[n, fill=green!20] (lr) at (-0.6,-1.7) {5};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
  \draw[very thick, red!60, rounded corners=4pt] (ll) -- (l) -- (lr);
  \node[font=\scriptsize, anchor=west] at (2.0,-0.8) {diameter = 3 via node 2};
\end{tikzpicture}
QQuestionWhy can the LCA of two nodes be one of the nodes themselves?
ASolution

If one node is an ancestor of the other, the deeper one is on every path between them, so it is the lowest common ancestor.

Balanced trees: AVL and red-black

A BST’s cost is its height. Balanced trees maintain \(h = O(\log n)\) by restructuring on insert and delete.

AVL trees keep the invariant |height(left) - height(right)| <= 1 at every node. A violation at the lowest unbalanced node is fixed by one of four rotations, chosen by the sign of the balance factor and the child’s balance:

Case Shape Fix
LL left-left heavy right rotation
RR right-right heavy left rotation
LR left child right-heavy left on child, right on node
RL right child left-heavy right on child, left on node
struct Node { int val, height = 1; Node *l = nullptr, *r = nullptr; };
int h(Node* n) { return n ? n->height : 0; }
void upd(Node* n) { n->height = 1 + max(h(n->l), h(n->r)); }

Node* rotRight(Node* y) {
    Node* x = y->l;
    Node* t = x->r;
    x->r = y; y->l = t;
    upd(y); upd(x);
    return x;
}
Node* rotLeft(Node* x) {
    Node* y = x->r;
    Node* t = y->l;
    y->l = x; x->r = t;
    upd(x); upd(y);
    return y;
}

A rotation is \(O(1)\) and preserves the inorder sequence — that is why it is safe. Insertion rebalances on the way back up the recursion, at most \(O(\log n)\) rotations.

Red-black trees allow a looser balance: the root is black, red nodes have black children, every path from a node to a leaf has the same number of black nodes. Height is at most \(2\log_2(n+1)\), so operations are \(O(\log n)\) with fewer rotations on average than AVL. std::map and std::set are red-black trees, which is why their iterators stay valid across inserts.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.62cm, font=\scriptsize\bfseries},
  a/.style={->, thick}]
  \node[n, fill=orange!25] (y) at (0,0) {30};
  \node[n] (x) at (-1.1,-0.85) {20};
  \node[n, fill=blue!15] (t) at (0.35,-0.85) {25};
  \node[n, fill=green!20] (z) at (-1.9,-1.7) {10};
  \draw[a] (y) -- (x); \draw[a] (y) -- (t); \draw[a] (x) -- (z);
  \node[font=\scriptsize, anchor=west] at (1.3,-0.4) {rotate right at 30};
  \node[font=\scriptsize, anchor=west] at (1.3,-0.9) {=> 20 becomes root};
\end{tikzpicture}
QQuestionWhy do AVL trees need at most one rotation per insertion but

red-black trees may need more restructuring per delete?

ASolution

AVL keeps a tight height bound and stops as soon as the first violation is fixed. Red-black has a looser invariant, so a deletion can require propagating recolours up the tree; either way it stays \(O(\log n)\).

Heaps and priority queues

A binary heap is a complete tree stored in an array, with the parent no smaller than its children (max-heap). std::priority_queue is a max-heap by default: push, pop, top in \(O(\log n)\), \(O(1)\), \(O(\log n)\).

priority_queue<int> maxHeap;                          // max on top
priority_queue<int, vector<int>, greater<int>> minHeap;  // min on top

The only operation that is not obvious is the \(O(n)\) build. Inserting n times is \(O(n \log n)\); sifting down from the last internal node is \(O(n)\).

void siftDown(vector<int>& h, int i) {
    int n = (int)h.size();
    while (true) {
        int l = 2*i + 1, r = l + 1, big = i;
        if (l < n && h[l] > h[big]) big = l;
        if (r < n && h[r] > h[big]) big = r;
        if (big == i) break;
        swap(h[i], h[big]);
        i = big;
    }
}
void buildHeap(vector<int>& h) {
    for (int i = (int)h.size()/2 - 1; i >= 0; --i) siftDown(h, i);
}

The proof of \(O(n)\): a node at height \(k\) costs \(O(k)\) to sift, and there are at most \(n/2^{k+1}\) such nodes, so the total is \(\sum k \cdot n/2^{k+1} = O(n)\).

Heaps are for “repeatedly take the extreme”: top-k, merge \(k\) lists, Dijkstra, task scheduling, median maintenance with two heaps. A heap is not a search structure — finding an arbitrary element is \(O(n)\).

QQuestionWhy is buildHeap linear when each siftDown can be \(O(\log n)\)?
ASolution

Most nodes are near the bottom and sift only a little. The weighted sum \(\sum_k k \cdot n/2^{k+1}\) converges to a constant times \(n\).

Tries

A trie stores strings by character path. Each node has up to 26 children and a flag marking the end of a word. Lookup costs \(O(L)\) in the key length, not in the number of keys.

struct TrieNode {
    TrieNode* child[26] = {};
    bool terminal = false;
};

void insert(TrieNode* root, const string& w) {
    TrieNode* n = root;
    for (char c : w) {
        int i = c - 'a';
        if (!n->child[i]) n->child[i] = new TrieNode();
        n = n->child[i];
    }
    n->terminal = true;
}
bool contains(TrieNode* root, const string& w) {
    TrieNode* n = root;
    for (char c : w) {
        int i = c - 'a';
        if (!n->child[i]) return false;
        n = n->child[i];
    }
    return n->terminal;
}

Prefix search is the same loop without the final terminal check — that is the autocomplete primitive. Wildcard search (. matches any letter) is a small DFS over the children.

Memory is the cost: 26 pointers is 208 bytes per node, so a million-node trie is 200 MB. For sparse alphabets use unordered_map<char, TrieNode*>, or a sorted vector of edges. For pure prefix counting, a hash map of prefixes is often simpler and faster.

Tries also solve “maximum XOR pair” (binary trie over 32 bits) and “longest common prefix”, and they are the structure behind a suffix trie.

QQuestionWhen is a trie better than a hash set of strings?
ASolution

When the query is a prefix, not a whole key. Hashing gives no prefix structure, so prefix queries need either a scan or a different container.

Rebuilding a tree from traversals

Preorder gives the root first. Inorder gives the split between left and right subtrees. Together they determine the tree.

TreeNode* build(const vector<int>& pre, const vector<int>& in) {
    unordered_map<int,int> idx;
    for (int i = 0; i < (int)in.size(); ++i) idx[in[i]] = i;
    int p = 0;
    function<TreeNode*(int,int)> go = [&](int l, int r) -> TreeNode* {
        if (l > r) return nullptr;
        int v = pre[p++];
        int m = idx[v];
        TreeNode* node = new TreeNode(v);
        node->left = go(l, m - 1);        // left subtree first: preorder
        node->right = go(m + 1, r);
        return node;
    };
    return go(0, (int)in.size() - 1);
}

The hash map turns the split lookup from \(O(n)\) into \(O(1)\), giving \(O(n)\) total instead of \(O(n^2)\) on a skewed tree.

Preorder and postorder alone are not enough. pre = [1,2], post = [2,1] fits both “2 is the left child” and “2 is the right child”; a single-child tree cannot be oriented from those two orders. Inorder resolves it. Postorder plus inorder works the same way with the root taken from the end.

QQuestionWhy can’t preorder and postorder reconstruct a unique binary tree?
ASolution

They reveal the root but not which side a lone child is on. A node with one child produces the same preorder and postorder whether that child is left or right.

Tree DP and rerooting

Tree DP is postorder recursion where each subtree returns a summary. The root’s answer is assembled from its children, and no state is shared across branches.

Subtree sums and sizes are the base case:

void dfs(int u, int parent, const vector<vector<int>>& g,
         vector<int>& sub) {
    sub[u] = 1;
    for (int v : g[u]) {
        if (v == parent) continue;
        dfs(v, u, g, sub);
        sub[u] += sub[v];
    }
}

Maximum path sum shows the “return one, use two” pattern: a node returns the best downward gain, but the answer may combine both children.

int best;
int gain(TreeNode* n) {
    if (!n) return 0;
    int l = max(0, gain(n->left));       // dropping a negative branch
    int r = max(0, gain(n->right));
    best = max(best, n->val + l + r);    // path through n, both sides
    return n->val + max(l, r);           // path to parent, one side
}

Rerooting computes an answer for every root in \(O(n)\) instead of \(O(n^2)\). The classic is the sum of distances from each node to all others. First pass: subtree sizes and the total distance from node 0. Second pass: move the root along an edge.

When the root moves from u to its child v, the sub[v] nodes in v’s subtree become one step closer, and the other n - sub[v] become one step farther:

\[ \text{dist}[v] = \text{dist}[u] + (n - \text{sub}[v]) - \text{sub}[v] = \text{dist}[u] + n - 2\,\text{sub}[v] \]

void reroot(int u, int parent, const vector<vector<int>>& g,
            const vector<int>& sub, vector<long long>& dist) {
    for (int v : g[u]) {
        if (v == parent) continue;
        dist[v] = dist[u] + (long long)g.size() - 2LL * sub[v];
        reroot(v, u, g, sub, dist);
    }
}

Two passes, \(O(n)\) total, and the formula generalizes: for any quantity that depends on distances, write how it changes when the root crosses one edge.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.7cm, font=\scriptsize\bfseries},
  a/.style={->, thick}]
  \node[n, fill=orange!25] (u) at (0,0) {u};
  \node[n, fill=green!20] (v) at (2.2,0) {v};
  \node[n] (s1) at (3.4,0.85) {};
  \node[n] (s2) at (3.4,-0.85) {};
  \draw[a] (u) -- (v); \draw[a] (v) -- (s1); \draw[a] (v) -- (s2);
  \draw[->, very thick, blue!60] (u) to[bend left=25] node[above, font=\scriptsize] {move root} (v);
  \node[font=\scriptsize, anchor=north] at (1.1,-0.75) {n - 2*sub[v]};
  \node[font=\scriptsize, anchor=west, text=green!45!black] at (3.9,0.4) {closer by 1};
\end{tikzpicture}
QQuestionWhy does rerooting avoid recomputing from scratch for each root?
ASolution

The answer for a neighbour differs from the current node by a fixed amount that depends only on the subtree size across that edge. Two passes over all edges suffice.

Bugs and edge cases

QQuestionYour diameter returns 0 for a two-node tree. What is wrong?
ASolution

The height convention or the update placement: with heights in nodes, the update must use l + r where a leaf returns 0, and the answer is in edges. If heights are in nodes, subtract 1 at the end.

Next: Graphs (DSA Core #6) — four traversals that solve almost everything, and SCCs as the one that needs its own proof.