Binary Tree Interview Questions for Freshers (with Code)

Top binary tree interview questions for freshers with tested Python code: traversals, level order, height, diameter, balanced tree, LCA, left view and more, with approach and complexity.

Why Binary Trees Come Up in So Many Interviews

Binary trees are one of the most frequently asked topics in technical interviews, from service companies like TCS, Infosys and Accenture to product companies. They test whether you understand recursion, which is a skill interviewers value highly.

The good news is that most tree questions follow the same few patterns. Once you learn to think recursively, problems like height, diameter, balanced tree and lowest common ancestor are all small variations of one idea.

This guide covers the key terms, the patterns behind most tree questions, and 10 must-do problems with tested Python code, approach and complexity. Level order traversal uses a queue, so if you have not read it yet, see our Stack and Queue Interview Questions guide first.

Binary Tree Basics in 2 Minutes

A binary tree is a structure where each node has at most two children, called left and right. The top node is the root, and nodes with no children are leaves.

TermMeaning
Height (depth)Number of nodes on the longest path from the root to a leaf
Full binary treeEvery node has 0 or 2 children
Complete binary treeAll levels full except possibly the last, which is filled from the left
Perfect binary treeAll internal nodes have 2 children and all leaves are at the same level
Balanced binary treeFor every node, left and right heights differ by at most 1
Binary search tree (BST)Left subtree values are smaller and right subtree values are larger than the node

Note on height: some textbooks count edges instead of nodes, so a single node has height 0 instead of 1. Both are accepted. Just say which one you are using in the interview.

Every example in this guide uses the tree below. Read the code comment to see its shape:

Python
class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

#        1
#       / \
#      2   3
#     / \   \
#    4   5   6
root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))

The Patterns Behind Most Tree Questions

1. Depth-first recursion (DFS). Most problems ask: "What does this node need from its left and right subtrees?" Solve the problem for both children, then combine the results. Height, diameter, balanced tree and LCA all work this way.

2. Breadth-first traversal (BFS). When the question mentions levels, such as level order, left view or zigzag traversal, use a queue to process the tree one level at a time.

3. Two-tree comparison. For identical, symmetric or mirror questions, recurse on two nodes at the same time and compare them.

Recognising which pattern a question needs is half the work. In the interview, say the pattern out loud before you start coding.

10 Must-Do Binary Tree Interview Questions

1. Inorder, Preorder and Postorder Traversal

Problem: Print the nodes of the tree in each of the three depth-first orders.

Example: For the example tree: inorder [4, 2, 5, 1, 3, 6], preorder [1, 2, 4, 5, 3, 6], postorder [4, 5, 2, 6, 3, 1].

Approach: The only difference is when you record the root: before the children (pre), between them (in) or after them (post).

Python
def inorder(node, out):     # Left, Root, Right
    if node:
        inorder(node.left, out)
        out.append(node.val)
        inorder(node.right, out)

def preorder(node, out):    # Root, Left, Right
    if node:
        out.append(node.val)
        preorder(node.left, out)
        preorder(node.right, out)

def postorder(node, out):   # Left, Right, Root
    if node:
        postorder(node.left, out)
        postorder(node.right, out)
        out.append(node.val)

Complexity: O(n) time. O(h) space for the recursion stack, where h is the height of the tree.

2. Level Order Traversal

Problem: Return the nodes level by level, from left to right.

Example: For the example tree: [[1], [2, 3], [4, 5, 6]].

Approach: Use a queue. At each step, process exactly as many nodes as the queue holds; that is one level.

Python
from collections import deque

def level_order(root):
    if not root:
        return []
    result, q = [], deque([root])
    while q:
        level = []
        for _ in range(len(q)):          # process one full level
            node = q.popleft()
            level.append(node.val)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
        result.append(level)
    return result

Complexity: O(n) time, O(w) space, where w is the maximum width of the tree.

3. Height (Maximum Depth) of a Tree

Problem: Find the number of nodes on the longest path from the root to a leaf.

Example: The example tree has height 3.

Approach: The height of a node is 1 plus the larger height of its two children. An empty tree has height 0.

Python
def height(node):
    if not node:
        return 0
    return 1 + max(height(node.left), height(node.right))

Complexity: O(n) time, O(h) space.

4. Diameter of a Binary Tree

Problem: Find the number of edges on the longest path between any two nodes. The path does not have to pass through the root.

Example: For the example tree, the path 4 → 2 → 1 → 3 → 6 has 4 edges, so the diameter is 4.

Approach: At every node, the longest path through it is left depth + right depth. Track the best value while computing depths in one pass. Calculating height separately at each node would make it O(n²).

Python
def diameter(root):
    best = 0
    def depth(node):
        nonlocal best
        if not node:
            return 0
        left, right = depth(node.left), depth(node.right)
        best = max(best, left + right)   # longest path through this node
        return 1 + max(left, right)
    depth(root)
    return best

Complexity: O(n) time, O(h) space.

5. Check if a Tree Is Balanced

Problem: Return True if, for every node, the heights of the left and right subtrees differ by at most 1.

Example: The example tree is balanced. A chain 1 → 2 → 3 is not.

Approach: Compute heights from the bottom up and return -1 as soon as any subtree is unbalanced, so you never recompute heights.

Python
def is_balanced(root):
    def check(node):                     # returns height, or -1 if unbalanced
        if not node:
            return 0
        left, right = check(node.left), check(node.right)
        if left == -1 or right == -1 or abs(left - right) > 1:
            return -1
        return 1 + max(left, right)
    return check(root) != -1

Complexity: O(n) time, O(h) space.

6. Mirror (Invert) a Binary Tree

Problem: Swap the left and right children of every node.

Example: Inorder of the mirrored example tree becomes [6, 3, 1, 5, 2, 4], the reverse of the original.

Approach: Swap the two children of the current node, then mirror each subtree recursively.

Python
def mirror(node):
    if node:
        node.left, node.right = node.right, node.left
        mirror(node.left)
        mirror(node.right)
    return node

Complexity: O(n) time, O(h) space.

7. Check if a Tree Is Symmetric

Problem: Return True if the tree is a mirror image of itself around its centre.

Example: 1 with children 2, 2 and grandchildren 3, 4, 4, 3 is symmetric. The example tree is not.

Approach: Compare the left subtree with the right subtree, matching outer children with outer children and inner with inner.

Python
def is_symmetric(root):
    def same(a, b):
        if not a and not b:
            return True
        if not a or not b or a.val != b.val:
            return False
        return same(a.left, b.right) and same(a.right, b.left)
    return same(root.left, root.right) if root else True

Complexity: O(n) time, O(h) space.

8. Lowest Common Ancestor (LCA)

Problem: Given two values p and q in the tree, find their lowest common ancestor: the deepest node that has both as descendants. A node counts as a descendant of itself.

Example: LCA(4, 5) = 2. LCA(4, 6) = 1. LCA(2, 4) = 2.

Approach: Search both subtrees. If p and q are found on different sides, the current node is the LCA. Otherwise, pass up whichever side found something. This version assumes both values exist in the tree.

Python
def lca(node, p, q):
    if not node or node.val == p or node.val == q:
        return node
    left = lca(node.left, p, q)
    right = lca(node.right, p, q)
    if left and right:
        return node            # p and q are on different sides
    return left or right

Complexity: O(n) time, O(h) space. For a BST, there is a faster O(h) method using the ordering.

9. Left View of a Binary Tree

Problem: Return the first node visible at each level when the tree is viewed from the left.

Example: For the example tree: [1, 2, 4].

Approach: Do a DFS that visits the left child first. The first node reached at each new depth is part of the left view. For the right view, visit the right child first.

Python
def left_view(root):
    view = []
    def visit(node, depth):
        if not node:
            return
        if depth == len(view):           # first node seen at this depth
            view.append(node.val)
        visit(node.left, depth + 1)
        visit(node.right, depth + 1)
    visit(root, 0)
    return view

Complexity: O(n) time, O(h) space. You can also solve it with level order by taking the first node of each level.

10. Root-to-Leaf Path Sum

Problem: Return True if some root-to-leaf path adds up to a target value.

Example: For the example tree, target 7 (1 + 2 + 4) and target 10 (1 + 3 + 6) return True. Target 3 returns False.

Approach: Subtract the current value from the target and pass the remainder down. At a leaf, check whether the remainder equals the leaf's value.

Python
def has_path_sum(node, target):
    if not node:
        return False
    if not node.left and not node.right:     # leaf node
        return node.val == target
    rest = target - node.val
    return has_path_sum(node.left, rest) or has_path_sum(node.right, rest)

Complexity: O(n) time, O(h) space.

Quick Revision Table

ProblemPatternTimeKey idea
Inorder / preorder / postorderDFSO(n)When to record the root
Level orderBFSO(n)Process queue size per level
HeightDFSO(n)1 + max(left, right)
DiameterDFSO(n)left + right at each node
BalancedDFSO(n)Return -1 early
MirrorDFSO(n)Swap children
SymmetricTwo-tree DFSO(n)Outer with outer, inner with inner
LCADFSO(n)Found on both sides = answer
Left viewDFS or BFSO(n)First node at each depth
Path sumDFSO(n)Pass the remainder down

Common Mistakes in Interviews

  • Forgetting the base case. Every recursive function must handle an empty node first. Most wrong answers crash on None.
  • Calling height inside a loop. Computing height separately at each node makes diameter and balanced-tree checks O(n²). Combine both in one pass.
  • Confusing binary tree with BST. A binary tree has no ordering rule. Do not assume left is smaller unless the question says BST.
  • Ignoring recursion depth. A very skewed tree with many nodes can exceed the recursion limit. Mention an iterative version if asked about large inputs.
  • Not stating complexity. Always give time and space complexity, and explain that space depends on the height h: O(log n) for balanced trees, O(n) for skewed ones.

How to Practise This Topic in One Week

  1. Day 1: Write the Node class and all three traversals from memory. Draw the call stack for a small tree on paper.
  2. Day 2: Solve level order traversal, then try zigzag level order as a variation.
  3. Day 3: Height, diameter and balanced tree. Focus on returning two pieces of information from one recursion.
  4. Day 4: Mirror, symmetric and identical trees.
  5. Day 5: LCA, left view and right view.
  6. Day 6: Path sum, then try printing all root-to-leaf paths.
  7. Day 7: Time yourself: two random problems in 40 minutes, explaining your approach out loud.

After binary trees, move on to binary search trees, then Graph Algorithms for Coding Rounds. A tree is a special kind of graph, so the DFS and BFS skills you build here carry over directly.

Frequently Asked Questions

What is the difference between a binary tree and a binary search tree?

A binary tree only requires each node to have at most two children. A binary search tree also requires every value in the left subtree to be smaller and every value in the right subtree to be larger than the node.

Which binary tree questions are asked most in placements?

Traversals, level order traversal, height, diameter, balanced tree check, mirror tree, lowest common ancestor and left or right view are among the most common.

Should I use recursion or iteration for tree problems?

Recursion is usually shorter and easier to explain, so start with it. Know the iterative version of traversals too, as some interviewers ask for it.

What is the space complexity of recursive tree solutions?

O(h), where h is the height of the tree, because of the recursion stack. This is O(log n) for a balanced tree and O(n) for a skewed one.

How is inorder traversal useful?

For a binary search tree, inorder traversal gives the values in sorted order. Many BST problems rely on this property.

Final Word

Most binary tree questions are the same recursive idea in different forms: solve the left subtree, solve the right subtree, then combine. Master the 10 problems above, say the pattern and complexity clearly, and you will handle most tree questions in placement interviews.

Continue with Stack and Queue Interview Questions, Linked List Interview Questions and our complete DSA for Campus Placements roadmap. For the theory round, see OOPs Interview Questions for Freshers.

Crack Your Placement with PlacementBaba

Free practice questions, mock tests and interview tipsStart Practicing — DSA Roadmap →