λDSA Learning Hubpart of DSA Atlas

Tree Fundamentals

Beginner~2h · 6 lessons6 practice problems

The vocabulary every tree question assumes: root, leaf, height vs depth, levels, subtrees, and balanced vs complete vs full shapes.

0 of 6 lessons checked off

Introduction

What it is

  • A tree is a connected structure with no cycles: n nodes, exactly n − 1 edges, and exactly one path between any two nodes. One node is designated the root; edges fan out downward to children.
  • This page is deliberately about words — root, leaf, depth, height, level, subtree, balanced, complete, full — because every tree problem statement is written in them.

Why it matters

  • Trees model every hierarchy you touch: file systems, DOM/UI components, org charts, JSON documents, decision processes, and database indexes.
  • Misreading one term costs whole solutions: confusing height with depth, or balanced with complete, sends your code to the wrong subtree entirely.

How it works

  • Structurally, a node holds a value plus references to children — a linked list that branches.
  • Everything is recursive: a tree is a root plus smaller trees. Algorithms mirror that — handle the node, recurse on children, combine.

Where it's used

  • Your filesystem is a tree you navigate daily; HTML is parsed into the DOM tree; compilers build abstract syntax trees; databases answer range queries with B-trees.

In interviews

  • Terminology check-ins ('what's the height of a single node?'), counting nodes/leaves, and as the foundation for the binary-tree, BST, heap, and trie pages that follow.
Analogy: A family tree drawn upside down: one ancestor at the top (root), descendants branching below, and 'find your cousin' always has exactly one path through a common ancestor.

Interactive diagram

Step through the vocabulary on one small tree — including the height-vs-depth trap.

16314108
A tree

A tree is a hierarchy of nodes connected by edges, with exactly one path between any two nodes. No cycles, ever.

Lessons in this topic

Check off lessons as you go — your progress is saved in this browser.

  1. Nodes, edges, and the no-cycle rule

    n nodes, n−1 edges, one path between any pair.

    15 min
  2. Root, parent, child, siblings

    The kinship vocabulary of hierarchy.

    10 min
  3. Leaf vs internal nodes

    Leaves end recursion; internal nodes forward it.

    10 min
  4. Height, depth, and level

    Opposite directions; level = depth + 1; the single-node edge case.

    20 min
  5. Subtrees and self-similarity

    Why tree code is recursive by nature.

    15 min
  6. Balanced, complete, full, degenerate

    Shape names and the complexity they imply.

    20 min

Operations

Measuring a tree: size, height, leaf count

Three one-liners that establish the recursive rhythm used by every tree algorithm: base case on None, recurse on children, combine.

Measuring a tree: size, height, leaf count
from typing import Optionalclass TreeNode:    def __init__(self, val: int = 0, left: "Optional[TreeNode]" = None,                 right: "Optional[TreeNode]" = None):        self.val, self.left, self.right = val, left, rightdef size(root: Optional[TreeNode]) -> int:    """Number of nodes. O(n)."""    if root is None:        return 0    return 1 + size(root.left) + size(root.right)def height(root: Optional[TreeNode]) -> int:    """Edges on the longest root-to-leaf path. Empty tree: -1, leaf: 0."""
Time: O(n) each — every node visited onceSpace: O(h) recursion stack

Edge cases

  • Empty tree: size 0, height −1 (edge convention) or 0 (node-count convention) — STATE which you use.
  • Single node: height 0 by the edge convention.
  • Degenerate tree: recursion depth n — mind Python's limit.

Common mistakes

  • Mixing height conventions mid-solution (edges vs nodes) — off-by-one everywhere.
  • Counting a None child as a leaf.

Complexity analysis

OperationBestAverageWorstSpace
Traverse all nodesO(n)O(n)O(n)O(h)
Height / size / leaf countO(n)O(n)O(n)O(h)
Search (unordered tree)O(1)O(n)O(n)O(h)

h = height: log n balanced, n degenerate. The h-vs-n distinction is the whole story of tree performance.

What interviewers expect you to know

Definitions you will be tested on

  • Depth(node): edges from the ROOT to it. Height(node): edges to its deepest LEAF. Height(tree) = height(root) = depth of deepest node.
  • Level = depth + 1 in most texts (root at level 1) — confirm the convention when a problem uses 'level'.
  • Complete: all levels full except possibly the last, filled left to right (heap shape). Full: every node has 0 or 2 children. Balanced: height O(log n) (AVL-style: subtree heights differ ≤ 1).
  • A tree with n nodes has n − 1 edges; max nodes at depth d is 2ᵈ (binary); max nodes in height-h binary tree is 2^(h+1) − 1.

Follow-ups to expect

  • "Height of an empty tree?" — −1 with edge counting, 0 with node counting; naming both shows fluency.
  • "Why does everything cost O(h)?" — paths from root bound the work; balance decides whether h is log n or n.

Common mistakes

Height vs depth swapped

They point opposite ways. Depth is measured from the root; height toward the leaves. The deepest node has max depth and height 0.

Complete vs full vs balanced conflated

A heap needs COMPLETE; 'full' and 'balanced' are different claims. Using them interchangeably leads to wrong assumptions about shape.

Assuming balance

Unless stated, a binary tree can be a path. Quote O(h) and note h = n worst case.

Miscounting edges vs nodes

A tree with n nodes has n − 1 edges, and a leaf's height is 0 edges (or 1 node, depending on convention). Slipping between edge-counting and node-counting mid-derivation is the most common source of off-by-one errors.

Treating a leaf's children as real nodes

A leaf's left/right are None, not empty subtrees to recurse into blindly — every recursive tree function must guard `if node is None` first, or it crashes one level below the leaves.

Practice problems

Hand-picked from the 355-problem DSA Atlas. Reveal hints and solutions progressively; mark and bookmark as you solve.

Easy (2)

Medium (4)

Topic quiz

4 questions across concepts, code output, complexity, and scenarios. Answer all, then submit for explanations.

  1. Concept1. A tree has 50 nodes. How many edges does it have?
  2. Concept2. Node X is at depth 3 in a tree of height 5. What is the height of X?
  3. Concept3. Which shape guarantee makes a binary tree's operations O(log n)?
  4. Complexity4. Maximum number of nodes in a binary tree of height h (edge convention)?

Frequently asked questions

Is a linked list a tree?

Structurally yes — a degenerate tree where every node has one child. That's exactly why unbalanced BSTs degrade to O(n): they become linked lists.

Why do different books give different heights for the same tree?

Two conventions: counting edges (leaf = 0, empty = −1) or counting nodes (leaf = 1, empty = 0). Both are fine; announce yours and stay consistent.

Summary & cheat sheet

Key takeaways

  • Tree = connected + acyclic: n nodes, n − 1 edges, one path between any pair.
  • Depth from the root; height toward the leaves; they meet only at extremes.
  • Complete = heap shape; full = 0/2 children; balanced = h ∈ O(log n).
  • All tree costs are O(h); balance is what makes h small.

Formulas & cheat sheet

  • edges = n − 1
  • max nodes at depth d = 2^d; max nodes with height h = 2^(h+1) − 1
  • balanced ⇒ h = O(log n); degenerate ⇒ h = n − 1

Interview checklist

  • I can define all nine terms without notes.
  • I can compute size/height/leaves recursively.
  • I state my height convention before using it.