Skip to main content
Quick Reference

Trees Cheatsheet

A tree on one page — roots, walks, and the traps around height, a skewed BST, and heap indexes.

10 sections 10 tables 14 code snippets

Root, leaves, and edges

Left and right

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

Stop on a missing node

if not node:
    return

The parts

PartMeaning
RootThe only node with no parent
LeafA node with no children
Edgen nodes give n - 1 edges. One path joins any pair
DepthEdges from the root. The root has depth 0
HeightEdges on the longest path down to a leaf. A leaf has height 0. An empty tree is -1
Binary nodeleft and right, each None or a node. A general node holds a list of children

This page is a tree. A graph is left out.

Full, complete, perfect

A level doubles

# depth d holds at most 2 ** d nodes

Three names people mix up

NameRule
FullEvery node has 0 or 2 children
CompleteEvery level is full except the last, and the last is packed from the left
PerfectEvery level is full. All leaves share one depth
Depth dAt most 2 ** d nodes. Depth 0 is the root
Perfect height h2 ** (h + 1) - 1 nodes. Height counts edges, so h = 0 is one node
Full countn is odd, and the leaf count is (n + 1) / 2

Four walks

Node, then left, then right

visit(node)
preorder(node.left)
preorder(node.right)

Left, then node, then right

inorder(node.left)
visit(node)
inorder(node.right)

Where each order is used

OrderVisit
PreorderNode, then left, then right. The root comes first
InorderLeft, then node, then right
PostorderLeft, then right, then node. Children finish before the parent
Level orderLeft to right across one depth, then the next depth
Inorder on a BSTValues come out low to high
Inorder on a plain treeLeft-node-right order only. It is not a sorted list

Binary search tree

Smaller goes left

if val < node.val:
    node = node.left
elif val > node.val:
    node = node.right

The order is on every descendant

RuleMeaning
Left sideEvery value in the left subtree is smaller than the node
Right sideEvery value in the right subtree is larger than the node
EqualThis page treats an equal value as found. A second copy needs a chosen side
SearchOne comparison drops a whole subtree
Sorted insertValues already in order make a chain. Search then costs O(n)
InorderThe walk prints the values from low to high

Delete a BST node

Two children keep both subtrees

# copy the successor value, then delete the successor

Three shapes

CaseMove
LeafThe parent link becomes None
One childThe parent points at that child
Two childrenCopy the successor value onto this node, then delete the successor
SuccessorThe smallest node in the right subtree. It has no left child
PredecessorThe largest node in the left subtree. Same idea, the other side
Unlink the node itselfOne of the two subtrees is dropped. Copy the value first

Level by level

Freeze this level before children join

width = len(dq)

A queue, one depth at a time

StepMeaning
Enqueue the rootThe first level is the root alone
Snapshot widthlen(dq) is this level. Children appended now wait for the next level
Dequeue that manyOne pass handles exactly one depth
Child links onlyEach node has one parent, so it is enqueued once
Skip NoneA missing left or right is not a node
Stack insteadThe latest node leaves first, so the walk dives down one branch

A heap is not a BST

0-based child slots

# left child is 2 * i + 1

Complete tree, stored in a list

IndexRule
Parent of i(i - 1) // 2, and only for i > 0
Left child2 * i + 1
Right child2 * i + 2
1-based listParent is i // 2, left is 2 * i, right is 2 * i + 1
Min-heap orderThe parent is <= both children. That is not the BST left-right split
Buildheapq.heapify is O(n). The smallest value sits at index 0

Keeping the height low

Left height minus right height

# factor = height(left) - height(right)

AVL and red-black

RuleMeaning
Balance factorheight(left) - height(right)
AVL nodeThe factor is -1, 0, or 1
Left heavy, factor +2If the left child is right-heavy, left-rotate that child first. Then right-rotate this node
Right heavy, factor -2If the right child is left-heavy, right-rotate that child first. Then left-rotate this node
Insert vs deleteInsert needs at most one rotation. Delete can rotate at several nodes on the way up
Red-blackThe root is black, a red node has black children, and every path to a nil leaf has the same black count

Time and stack space

Empty is -1, so a leaf is 0

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

Balance changes the cost

WorkCost
Any of the four walksO(n) time. Each node is visited once
Recursive walkO(h) stack frames. A chain uses O(n) frames
Balanced searchO(log n)
Skewed searchO(n). The tree is a linked chain
Level-order queueO(w) extra space. A perfect tree puts (n + 1) / 2 nodes on the last level
n pushes vs heapifyn calls to heappush cost O(n log n). heapq.heapify costs O(n)

Interview traps

Sorted only for a BST

# inorder of a plain tree is not sorted

A stack dives

# a stack walk is depth-first

A missing node has no child

# node.left when node is None raises AttributeError

Traps worth memorising

TrapWhat happensPrefer
Node-count heightA lone root comes out as 1Edge height: that root is 0, and empty is -1
Inorder means sortedA plain tree prints left-node-right, not low to highCheck the BST order first
Stack for levelsThe latest node leaves firstA queue, and take one width per level
None.leftAttributeErrorTest the node before the read
Unlink a two-child nodeOne subtree disappearsCopy the successor, then delete that successor
1-based formula on a 0-based listThe child indexes land on the wrong slots2 * i + 1 and 2 * i + 2

How to use this page: count edges for height, trust inorder for sorted output only on a BST, and use a queue for one level.