A quick reference for tree techniques and problems to practice. Trees are one of the most important data structures in computer science and appear frequently in coding interviews. A tree is a hierarchical data structure consisting of nodes connected by edges, where each node has at most one parent and can have multiple children.Binary trees, where each node has at most two children, are the most common type in interviews. Understanding how to traverse trees, reason about their structure recursively, and apply the properties of binary search trees is essential. Most tree problems follow predictable patterns once you learn to identify them, and nearly all of them can be solved using some form of depth-first or breadth-first traversal.
Key Concepts
The table below lists the fundamental tree traversal methods and properties. Each traversal processes nodes in a different order, and choosing the right one depends on the problem requirements.
Concept
Description
DFS (Preorder)
Node → Left → Right
DFS (Inorder)
Left → Node → Right (sorted for BST)
DFS (Postorder)
Left → Right → Node
BFS (Level Order)
Level by level using queue
BST Property
Left < Node < Right
When to Use Each Traversal
Preorder (Node-Left-Right): Useful when you need to process the current node before its children. Common for creating a copy of a tree or serializing a tree structure.
Inorder (Left-Node-Right): Essential for binary search trees because it visits nodes in sorted order. Use it whenever you need to validate BST properties or extract sorted data.
Postorder (Left-Right-Node): Useful when you need information from children before processing the parent. Common for calculating tree height, deleting a tree, or evaluating expressions.
BFS (Level Order): Use when you need to process nodes level by level. Essential for problems involving minimum depth, right side view, or connecting nodes at the same level.
Recursive Thinking for Trees
The key insight for most tree problems is to think recursively: solve the problem for the left subtree, solve it for the right subtree, and combine the results at the current node. This pattern applies to a surprising number of problems, from calculating the maximum depth to finding the diameter of a tree.When writing recursive tree solutions, always start by defining your base case (usually when the node is null) and then determine what information you need from the left and right subtrees to solve the problem at the current node. This bottom-up approach makes even complex tree problems manageable.