# Most Common Tree Interview Questions (With C++ Solutions)

> Tree interview questions from easy to hard: height, diameter, LCA, symmetric, balanced, build from traversals and serialize, with tested C++ solutions.

- Canonical URL: https://shafinchowdhury.dev/posts/tree-interview-questions/
- Author: Shafin Chowdhury (https://shafinchowdhury.dev/about/)
- Published: 2026-12-04T03:10:00.000Z
- Updated: 2026-12-04T03:10:00.000Z
- Reading Time: 11 min read
- Tags: cpp, data-structures, trees, binary-tree, interview

---

import Diagram from "@/components/Diagram.astro";

Tree questions test one skill above all: **writing a recursive function that trusts its recursive calls**. Almost every problem below follows the same pattern: handle `nullptr`, ask the left and right subtrees for an answer, and combine the two answers at the current node. Master that pattern and most "new" tree questions turn into small variations.

This article collects the binary tree questions that come up most often in software engineering interviews, grouped into **foundational concepts**, **easy coding**, **medium**, and **hard**. Each coding question has the problem, intuition, an example, a tested C++ solution, complexity, and the follow-ups interviewers tend to ask next.

> **Tree & Graph series, step 3 of 8.** Prerequisites: [Trees, Binary Trees & Traversals](/posts/tree-binary-tree-traversals/) and [Binary Search Tree](/posts/binary-search-tree-bst/). Next: [BST Interview Questions](/posts/bst-interview-questions/).

---

## How to Use This List

| Level | Questions | What it tests |
| --- | --- | --- |
| Foundational (concepts) | 1–8 | Vocabulary; you must answer these in one or two sentences |
| Easy (coding) | 9–16 | The basic recursion template |
| Medium | 17–22 | Combining two results, BFS, global answers |
| Hard | 23–24 | Design and reconstruction |

All code uses the LeetCode-style node below. `n` is the number of nodes and `h` the height. Every solution was compiled with `-Wall -Wextra` and checked against the examples shown, under AddressSanitizer.

```cpp
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
```

**The universal template.** Write down what your function returns for one subtree, then:

```text
solve(node):
    if node is null: return the answer for an empty tree
    L = solve(node.left)
    R = solve(node.right)
    return combine(node, L, R)
```

---

## Foundational Concept Questions

### 1. What is a tree?

A tree is a hierarchical, non-linear data structure of nodes connected by edges, with one root, exactly one parent for every other node, and no cycles. A tree with $n$ nodes has $n - 1$ edges. A tree is a connected acyclic graph, which is why tree algorithms are special cases of [DFS and BFS](/posts/what-is-dfs-and-bfs/).

### 2. Binary tree vs binary search tree?

A **binary tree** only limits each node to two children. A **BST** adds an ordering rule: every key in a node's left subtree is smaller and every key in its right subtree is larger. That rule makes search $O(h)$ instead of $O(n)$ and makes inorder traversal sorted. Details: [BST guide](/posts/binary-search-tree-bst/).

### 3. Binary tree vs binary heap?

| | Binary search tree | Binary heap |
| --- | --- | --- |
| Shape | Any shape | Must be a **complete** binary tree |
| Order rule | left < node < right (whole subtrees) | parent ≤ children (min-heap) or ≥ (max-heap) |
| Find min | $O(h)$ (leftmost) | $O(1)$ (root) |
| Search any key | $O(h)$ | $O(n)$ |
| Storage | Pointers | An array, no pointers |
| Used for | Ordered sets/maps | Priority queues, heap sort |

A heap is a binary tree but not a BST.

### 4. Height vs depth?

**Depth** of a node = number of edges from the root down to it (the root has depth 0). **Height** of a node = number of edges on the longest path from it down to a leaf (a leaf has height 0). The height of the tree is the height of the root, which equals the maximum depth of any node. Interviewers sometimes count nodes instead of edges, for example LeetCode's "maximum depth", so state your convention.

### 5. What is a balanced tree?

A binary tree is **height-balanced** if, at **every** node, the heights of the left and right subtrees differ by at most 1. Balanced trees have height $O(\log n)$, which keeps operations fast. AVL trees enforce exactly this rule; red-black trees use a looser rule with the same $O(\log n)$ guarantee.

### 6. What is a complete binary tree?

Every level is full except possibly the last, and the last level's nodes are as far **left** as possible. A complete tree can be stored in an array with no gaps (children of index `i` at `2i+1` and `2i+2`), which is why heaps use it.

### 7. What is a full binary tree?

Every node has **0 or 2** children, never exactly one. In a full binary tree, leaves = internal nodes + 1. Do not confuse it with a **perfect** tree, where additionally all leaves are on the same level. See the [types diagram](/posts/tree-binary-tree-traversals/#types-of-binary-trees).

### 8. Explain inorder, preorder, and postorder.

They are the three depth-first orders and differ only in when the root is visited:

- **Preorder** (Root, Left, Right): copy or serialize a tree; first element is the root.
- **Inorder** (Left, Root, Right): sorted order on a BST.
- **Postorder** (Left, Right, Root): delete a tree, compute heights, evaluate expression trees; last element is the root.

For the tree `1(2(4, 5(7)), 3(-, 6))`: preorder `1 2 4 5 7 3 6`, inorder `4 2 7 5 1 3 6`, postorder `4 7 5 2 6 3 1`. Step-by-step traces with an interactive player are in the [traversals guide](/posts/tree-binary-tree-traversals/#tree-traversal-inorder-preorder-postorder-and-level-order).

---

## Easy Coding Questions

### 9. Implement all three traversals (recursively and iteratively)

**Problem.** Return the preorder, inorder and postorder of a binary tree as vectors.

**Intuition.** One recursive helper per order; only the position of `out.push_back` moves.

```cpp
void preorderHelper(TreeNode* node, vector<int>& out) {
    if (!node) {
        return;
    }
    out.push_back(node->val);
    preorderHelper(node->left, out);
    preorderHelper(node->right, out);
}
void inorderHelper(TreeNode* node, vector<int>& out) {
    if (!node) {
        return;
    }
    inorderHelper(node->left, out);
    out.push_back(node->val);
    inorderHelper(node->right, out);
}
void postorderHelper(TreeNode* node, vector<int>& out) {
    if (!node) {
        return;
    }
    postorderHelper(node->left, out);
    postorderHelper(node->right, out);
    out.push_back(node->val);
}
vector<int> preorderTraversal(TreeNode* root) {
    vector<int> out;
    preorderHelper(root, out);
    return out;
}
vector<int> inorderTraversal(TreeNode* root) {
    vector<int> out;
    inorderHelper(root, out);
    return out;
}
vector<int> postorderTraversal(TreeNode* root) {
    vector<int> out;
    postorderHelper(root, out);
    return out;
}
```

**The common follow-up: "now do inorder without recursion."** Simulate the call stack. Push nodes while going left; when you cannot go further left, pop, visit, and move to the right child.

```cpp
vector<int> inorderIterative(TreeNode* root) {
    vector<int> out;
    stack<TreeNode*> st;
    TreeNode* current = root;
    while (current || !st.empty()) {
        while (current) {          // go as far left as possible
            st.push(current);
            current = current->left;
        }
        current = st.top();        // leftmost unvisited node
        st.pop();
        out.push_back(current->val);
        current = current->right;  // then its right subtree
    }
    return out;
}
```

**Complexity.** $O(n)$ time, $O(h)$ space for both versions.

**Follow-ups.** Iterative preorder (push right child before left), iterative postorder (two stacks, or reverse a Root-Right-Left preorder), and **Morris traversal**, which does inorder in $O(1)$ extra space by temporarily threading `right` pointers.

### 10. Find the height (maximum depth) of a binary tree

Interviewers ask this as "height" or "maximum depth"; it is the same problem, usually counted in nodes.

**Problem.** Return the number of nodes on the longest root-to-leaf path (LeetCode 104 convention).

**Example.** For `3(9, 20(15, 7))` the answer is 3.

**Intuition.** The depth of a tree is 1 (for the root) plus the deeper of its two subtrees.

```cpp
int maxDepth(TreeNode* root) {
    if (!root) {
        return 0;
    }
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
```

**Complexity.** $O(n)$ time, $O(h)$ space.

**Follow-ups.** Height in edges = `maxDepth - 1` (−1 for an empty tree). **Minimum** depth: careful, a node with one child is not a leaf, so you cannot just take `min(L, R)`. Iterative version: BFS and count levels.

<Diagram
  src="tree-interview-questions/height-and-diameter"
  alt="Two copies of the same tree. Left: the height path 1, 2, 4, 6, 8 is highlighted, length 4 edges. Right: the diameter path 8, 6, 4, 2, 5, 7, 9 is highlighted, length 6 edges, and it does not pass through the root 1."
/>

### 11. Count the number of nodes

```cpp
int countNodes(TreeNode* root) {
    if (!root) {
        return 0;
    }
    return 1 + countNodes(root->left) + countNodes(root->right);
}
```

$O(n)$ time, $O(h)$ space. **Follow-up:** for a **complete** tree, compare the leftmost and rightmost depths; if equal, the subtree is perfect and has $2^d - 1$ nodes. This gives $O(\log^2 n)$ (LeetCode 222).

### 12. Count leaf nodes

A leaf has **both** children null.

```cpp
int countLeaves(TreeNode* root) {
    if (!root) {
        return 0;
    }
    if (!root->left && !root->right) {
        return 1;
    }
    return countLeaves(root->left) + countLeaves(root->right);
}
```

$O(n)$ time. **Follow-up:** internal nodes = total − leaves; nodes with two children = leaves − 1.

### 13. Find the maximum value in a binary tree

The tree is **not** a BST, so the maximum can be anywhere. Check all nodes.

```cpp
int findMax(TreeNode* root) {
    if (!root) {
        return INT_MIN; // identity for max; callers should check for an empty tree
    }
    return max({root->val, findMax(root->left), findMax(root->right)});
}
```

$O(n)$ time. **Follow-up:** in a BST it is just the rightmost node, $O(h)$.

### 14. Search for an element in a binary tree

```cpp
bool containsValue(TreeNode* root, int target) {
    if (!root) {
        return false;
    }
    if (root->val == target) {
        return true;
    }
    return containsValue(root->left, target) || containsValue(root->right, target);
}
```

$O(n)$ time worst case; `||` short-circuits, so the right subtree is skipped once the left finds the target. In a BST this becomes $O(h)$.

### 15. Check whether two trees are identical

**Problem.** Same shape and same values at every position (LeetCode 100).

**Intuition.** Two trees are identical if both are empty, or both roots match and both pairs of subtrees are identical.

```cpp
bool isSameTree(TreeNode* p, TreeNode* q) {
    if (!p || !q) {
        return p == q; // both null: true; exactly one null: false
    }
    return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
```

$O(\min(n_1, n_2))$ time. **Follow-up:** "Is `t` a subtree of `s`?" Call `isSameTree` from every node of `s` ($O(n \cdot m)$), or serialize both and use string matching.

### 16. Invert a binary tree

**Problem.** Mirror the tree: swap every node's left and right children (LeetCode 226).

<Diagram
  src="tree-interview-questions/invert-binary-tree"
  alt="Before: tree 4 with children 2 and 7, where 2 has children 1 and 3 and 7 has children 6 and 9. After inversion: 4 with children 7 and 2, where 7 has children 9 and 6 and 2 has children 3 and 1."
/>

```cpp
TreeNode* invertTree(TreeNode* root) {
    if (!root) {
        return nullptr;
    }
    swap(root->left, root->right);
    invertTree(root->left);
    invertTree(root->right);
    return root;
}
```

Level order changes from `4 2 7 1 3 6 9` to `4 7 2 9 6 3 1`. $O(n)$ time, $O(h)$ space. **Follow-up:** do it iteratively with a queue (swap children of each dequeued node).

---

## Medium Questions

### 17. Check whether a tree is symmetric

**Problem.** Is the tree a mirror image of itself around its centre (LeetCode 101)?

<Diagram
  src="tree-interview-questions/symmetric-tree"
  alt="Left: symmetric tree 1 with children 2 and 2, whose children are 3, 4 and 4, 3. Right: tree 1 with children 2 and 2, each having only a right child 3, which is not symmetric."
/>

**Intuition.** Compare the left subtree with the **mirror** of the right subtree: outer pairs (`a->left`, `b->right`) and inner pairs (`a->right`, `b->left`) must match.

```cpp
bool isMirror(TreeNode* a, TreeNode* b) {
    if (!a || !b) {
        return a == b;
    }
    return a->val == b->val && isMirror(a->left, b->right) && isMirror(a->right, b->left);
}
bool isSymmetric(TreeNode* root) {
    return !root || isMirror(root->left, root->right);
}
```

**Step by step** for `[1, 2, 2, 3, 4, 4, 3]`: compare 2 and 2 (equal), then their outer children 3 and 3, then inner children 4 and 4. All match → `true`. For `[1, 2, 2, null, 3, null, 3]`: the outer pair is (null, 3) → `false`.

$O(n)$ time, $O(h)$ space. **Follow-up:** iterative version with a queue holding pairs.

### 18. Find the diameter of a binary tree

**Problem.** The diameter is the number of **edges** on the longest path between any two nodes (LeetCode 543). The path does not have to pass through the root (see the diagram under question 10: diameter 6 through node 2).

**Intuition.** The longest path that "bends" at a node has length `height(left) + height(right)` measured in nodes below it. Compute heights bottom-up and update a global best at every node, in one pass.

```cpp
int depthAndDiameter(TreeNode* node, int& best) {
    if (!node) {
        return 0;
    }
    int left = depthAndDiameter(node->left, best);
    int right = depthAndDiameter(node->right, best);
    best = max(best, left + right);  // longest path bending at this node
    return 1 + max(left, right);     // depth (in nodes) for the parent
}
int diameterOfBinaryTree(TreeNode* root) {
    int best = 0;
    depthAndDiameter(root, best);
    return best;
}
```

**Complexity.** $O(n)$ time. Calling a separate `height()` from every node is $O(n^2)$ on a skewed tree; returning the height and updating the answer in the same pass is the key insight interviewers look for.

**Follow-ups.** Return the path itself; **binary tree maximum path sum** (LeetCode 124) uses the identical structure with sums and `max(0, child)`.

### 19. Check whether a binary tree is balanced

**Intuition.** Return the height, or a sentinel `-1` meaning "already unbalanced", so each node is processed once.

```cpp
int balancedHeight(TreeNode* node) {
    if (!node) {
        return 0;
    }
    int left = balancedHeight(node->left);
    if (left == -1) {
        return -1;
    }
    int right = balancedHeight(node->right);
    if (right == -1) {
        return -1;
    }
    if (abs(left - right) > 1) {
        return -1;
    }
    return 1 + max(left, right);
}
bool isBalanced(TreeNode* root) {
    return balancedHeight(root) != -1;
}
```

$O(n)$ time, $O(h)$ space. **Common wrong answer:** checking only the root's two subtrees. The condition must hold at **every** node.

### 20. Level-order traversal (grouped by level)

**Problem.** Return the values level by level: `[[3], [9, 20], [15, 7]]` (LeetCode 102).

**Intuition.** BFS with a queue. Before processing a level, record `q.size()`: exactly that many nodes belong to the current level.

```cpp
vector<vector<int>> levelOrder(TreeNode* root) {
    vector<vector<int>> levels;
    if (!root) {
        return levels;
    }
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        int count = q.size();            // nodes on this level
        vector<int> level;
        for (int i = 0; i < count; ++i) {
            TreeNode* node = q.front();
            q.pop();
            level.push_back(node->val);
            if (node->left) {
                q.push(node->left);
            }
            if (node->right) {
                q.push(node->right);
            }
        }
        levels.push_back(level);
    }
    return levels;
}
```

$O(n)$ time, $O(w)$ space where $w$ is the maximum width. **Follow-ups:** zigzag order (reverse every other level), right side view (last node of each level), average of each level, minimum depth via BFS (stop at the first leaf). Why BFS here and not DFS? See [DFS vs BFS](/posts/dfs-vs-bfs/).

### 21. Lowest common ancestor (LCA) of a binary tree

**Problem.** Given two nodes `p` and `q` in a binary tree (not a BST), find their deepest common ancestor. A node is allowed to be an ancestor of itself (LeetCode 236).

<Diagram
  src="tree-interview-questions/lowest-common-ancestor"
  alt="Tree 1 with children 2 and 3. 2 has children 4 and 5, 5 has child 7, 3 has child 6. Nodes 4 and 7 are highlighted and the path 4, 2, 5, 7 is drawn. Node 2 is marked as their lowest common ancestor."
/>

**Intuition.** Ask each subtree "did you find `p` or `q`?"

- If the current node is `p` or `q`, return it.
- If **both** subtrees return non-null, `p` and `q` are on different sides, so the current node is the LCA.
- Otherwise pass up whichever side found something.

```cpp
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    if (!root || root == p || root == q) {
        return root;
    }
    TreeNode* left = lowestCommonAncestor(root->left, p, q);
    TreeNode* right = lowestCommonAncestor(root->right, p, q);
    if (left && right) {
        return root; // p and q split here
    }
    return left ? left : right;
}
```

**Trace for LCA(4, 7)** on the diagram: at 1, the left call (subtree 2) and right call (subtree 3) run. Inside subtree 2, the left call returns 4 and the right call (subtree 5) returns 7, so node 2 gets two non-null answers and returns itself. Subtree 3 returns null. Node 1 passes up 2. Answer: **2**.

$O(n)$ time, $O(h)$ space. **Follow-ups:** what if `p` or `q` might be missing (count how many were found)? With parent pointers it becomes "intersection of two linked lists". In a **BST** it is $O(h)$; see the [BST interview questions](/posts/bst-interview-questions/#8-lowest-common-ancestor-in-a-bst).

### 22. Construct a binary tree from preorder and inorder traversals

**Problem.** Given preorder and inorder of a tree with **distinct** values, rebuild it (LeetCode 105).

**Example.** preorder `3 9 20 15 7`, inorder `9 3 15 20 7` → `3(9, 20(15, 7))`.

**Intuition.**

1. The first preorder value is the root.
2. Find it in inorder: everything to its left is the left subtree, everything to its right is the right subtree.
3. The next values in preorder are the left subtree's preorder, then the right subtree's. Recurse.

```cpp
TreeNode* buildRange(const vector<int>& preorder, int& next,
                     const unordered_map<int, int>& indexInInorder, int lo, int hi) {
    if (lo > hi) {
        return nullptr;
    }
    int rootVal = preorder[next++];
    TreeNode* root = new TreeNode(rootVal);
    int mid = indexInInorder.at(rootVal);
    root->left = buildRange(preorder, next, indexInInorder, lo, mid - 1);  // left first: matches preorder
    root->right = buildRange(preorder, next, indexInInorder, mid + 1, hi);
    return root;
}
TreeNode* buildTree(const vector<int>& preorder, const vector<int>& inorder) {
    unordered_map<int, int> indexInInorder;
    for (int i = 0; i < (int)inorder.size(); ++i) {
        indexInInorder[inorder[i]] = i;
    }
    int next = 0;
    return buildRange(preorder, next, indexInInorder, 0, (int)inorder.size() - 1);
}
```

**Complexity.** $O(n)$ time with the hash map (searching inorder linearly each time would be $O(n^2)$), $O(n)$ space.

**Follow-ups.** Postorder + inorder: take roots from the **end** of postorder and build the **right** subtree first. Preorder + postorder: unique only for full binary trees. Duplicates break uniqueness. A worked paper example is in the [tree exam guide](/posts/tree-questions-university-exams-bangladesh/).

---

## Hard Questions

### 23. Serialize and deserialize a binary tree

**Problem.** Convert a tree to a string and back, so the rebuilt tree is identical (LeetCode 297).

**Intuition.** One traversal is not enough to rebuild a tree, **unless you also record the nulls**. Preorder with a marker for every null child is unambiguous: the reader always knows whether the next token is a node or an empty subtree.

```cpp
void serializeHelper(TreeNode* node, string& out) {
    if (!node) {
        out += "# ";
        return;
    }
    out += to_string(node->val) + ' ';
    serializeHelper(node->left, out);
    serializeHelper(node->right, out);
}
string serialize(TreeNode* root) {
    string out;
    serializeHelper(root, out);
    return out;
}
TreeNode* deserializeHelper(istringstream& in) {
    string token;
    if (!(in >> token) || token == "#") {
        return nullptr;
    }
    TreeNode* node = new TreeNode(stoi(token));
    node->left = deserializeHelper(in);   // same order as serialize
    node->right = deserializeHelper(in);
    return node;
}
TreeNode* deserialize(const string& data) {
    istringstream in(data);
    return deserializeHelper(in);
}
```

**Example.** `1(2, 3(4, 5))` serializes to `1 2 # # 3 4 # # 5 # #`. Deserializing reads `1`, then builds its left subtree from `2 # #` and its right from `3 4 # # 5 # #`.

**Complexity.** $O(n)$ time and space for both directions.

**Follow-ups.** Level-order format (LeetCode's own), compact binary encoding, a BST version that needs no null markers (preorder plus bounds, see [BST question 18](/posts/bst-interview-questions/#18-construct-a-bst-from-preorder-traversal)), and very deep trees (switch to an iterative stack to avoid stack overflow).

### 24. Bonus: what interviewers ask after you finish

Be ready to answer, for any solution above:

- **"What if the tree has a million nodes in a straight line?"** Recursion depth becomes a million and will overflow the default stack. Convert to an iterative solution with an explicit stack or queue.
- **"Can you do it in one pass?"** Diameter and balanced-check are the classic examples where returning height and updating a global answer avoids $O(n^2)$.
- **"What's the space complexity?"** It is $O(h)$ for recursive DFS, not $O(1)$; and $O(w)$ for BFS.
- **"Does it work for an empty tree?"** Test `nullptr`, a single node, and a skewed tree before you say you are done.

---

## Summary Table

| # | Question | Technique | Time | Space |
| --- | --- | --- | --- | --- |
| 9 | Traversals | Recursion / stack | $O(n)$ | $O(h)$ |
| 10 | Height / max depth | Postorder return value | $O(n)$ | $O(h)$ |
| 11–14 | Count, leaves, max, search | Template | $O(n)$ | $O(h)$ |
| 15 | Identical trees | Parallel recursion | $O(n)$ | $O(h)$ |
| 16 | Invert | Swap + recurse | $O(n)$ | $O(h)$ |
| 17 | Symmetric | Mirror recursion | $O(n)$ | $O(h)$ |
| 18 | Diameter | Height + global best | $O(n)$ | $O(h)$ |
| 19 | Balanced | Height or −1 | $O(n)$ | $O(h)$ |
| 20 | Level order | BFS with level size | $O(n)$ | $O(w)$ |
| 21 | LCA | Return found nodes | $O(n)$ | $O(h)$ |
| 22 | Build from traversals | Root split + hash map | $O(n)$ | $O(n)$ |
| 23 | Serialize | Preorder with nulls | $O(n)$ | $O(n)$ |

## Frequently Asked Questions

### Which tree questions should I learn first?

Traversals, max depth, same tree, invert and level order. They teach the two core patterns (recursive DFS and queue-based BFS) that every other question reuses.

### Recursive or iterative in an interview?

Start with the recursive solution, which is shorter and easier to get right, and mention the $O(h)$ stack cost. Offer an iterative version if the interviewer asks about very deep trees.

### How is a tree question different from a BST question?

In a general binary tree you usually have to look at every node. In a BST, the ordering lets you discard half the tree at each step. If the problem says "BST", use that property, or the interviewer will ask why you did not. Continue with the [BST interview questions](/posts/bst-interview-questions/).

## Next Steps

1. **Next:** [Most Common BST Interview Questions](/posts/bst-interview-questions/).
2. Preparing for university exams instead? [Tree Questions for University Exams in Bangladesh](/posts/tree-questions-university-exams-bangladesh/).
3. Level order is BFS in disguise: [DFS vs BFS](/posts/dfs-vs-bfs/) explains both on general graphs.
