If you already write programs but have never sat down with trees, this helper post is for you. A tree looks formal in a textbook, yet you already use the idea every day. Your computer’s folders, a family tree in a wedding album, and the HTML behind a web page are all trees. Once you can see that picture, the interview problems start to feel like ordinary code.
Keep this page open as you move into the trees section of the Tekraze DSA series. The first trees post in the series is Invert Binary Tree, and the one after that is Maximum Depth of a Binary Tree. You do not need those solutions yet. You only need a clear picture of what a tree is, how a graph is different, and how to start solving.
Also Read: the recursion helper if a function that calls itself still feels abstract, the Data Structures Cheat Sheet for a one page tour of trees and graphs, and the Big O helper whenever we talk about time and space.
What is a tree in simple words?
Think of a family tree drawn from one ancestor. That ancestor sits at the top. Under them come their children, then grandchildren, and so on. Every person has at most one parent in that drawing. Nobody is their own grandparent. That is a tree. The same shape appears on your disk. A folder can hold files and other folders, each item lives in one folder, and a folder cannot contain itself.
In code, each person or folder is a node. The first node is the root. The connections are edges. Information hangs downward from the root, and it never loops back. If it did loop, you would no longer have a tree. You would have a more general graph, which we will come to later.
A linked list is actually a very skinny tree. Each node has only one child, called next. A binary tree simply gives a node up to two children, usually named left and right. If you have already followed Day 18, Reverse Linked List, you have already been walking a tree with one child.
What are the parts of a tree?
These names show up in almost every tree problem. Learn them once, and the statements start to read like English.

- Node. One item in the tree, holding a value and links to its children.
- Edge. The link between two nodes, like the line from a parent to a child.
- Root. The starting node. It has no parent. In the picture, that is A.
- Parent and child. If there is an edge from A down to B, then A is the parent and B is the child. A parent can have several children. A child has only one parent.
- Leaf. A node with no children. D, E and F are leaves. Work often stops here.
- Subtree. A node plus everything under it. The subtree of B is B, D and E.
- Depth of a node. How far that node sits from the root. Counting edges, the root has depth 0 and D has depth 2. Counting nodes on the path, the root has depth 1 and D has depth 3.
- Height of a tree. The length of the longest path from the root down to a leaf. In the picture that is 2 edges, or 3 nodes.
That last split catches a lot of people. In textbooks, height and depth usually count edges, so a tree with only a root has height 0. On LeetCode, “maximum depth” counts nodes on the path, so a tree with only a root has depth 1, and an empty tree has depth 0. LeetCode 104 Maximum Depth of Binary Tree uses the node count. When an interviewer says height or depth, ask which one they mean. It takes five seconds and avoids an off-by-one.
Which kinds of trees show up in interviews?
You do not need every textbook variety. These three cover almost everything this series will ask of you.
Binary tree
Every node has at most two children, left and right. Either child can be missing. This is the default tree in interview problems, including LeetCode 226 Invert Binary Tree and LeetCode 104 Maximum Depth of Binary Tree.
Binary search tree
A binary tree with one extra rule. Everything in the left subtree is smaller than the node, and everything in the right subtree is bigger. Searching then feels like Day 23, Binary Search. You look at the node, throw away one side, and repeat. In a balanced BST this is O(log n). If you insert already sorted values into a plain BST, it can grow into a long stick and slow down to O(n). Library maps such as Java’s TreeMap and Rust’s BTreeMap keep themselves balanced so that does not happen.
N-ary or general tree
A node may have any number of children, stored as a list. Folders, org charts and the HTML DOM are n-ary trees. The idea does not change. Instead of calling left and right, you loop over children.
You may also hear full and complete. A full binary tree means every node has 0 or 2 children, never one. A complete binary tree fills every level except possibly the last, and the last level fills from the left. Heaps are complete, which is why they fit neatly into an array. You rarely need these words to start solving. They help when someone talks about the shape of a heap.
How do you represent a tree in code?
You almost never store a tree as a big grid. You store one node, and that node points at its children. For a binary tree the node has a value, a left child and a right child. For an n-ary tree it has a list of children. The empty child is null in Java, None in Python, and None in Rust.
Java
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
class NaryNode {
String val;
List<NaryNode> children = new ArrayList<>();
NaryNode(String val) { this.val = val; }
}
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class NaryNode:
def __init__(self, val=0, children=None):
self.val = val
self.children = children or []
Rust
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
struct NaryNode {
val: String,
children: Vec<NaryNode>,
}
On LeetCode, the Rust tree node is usually wrapped in Rc<RefCell<TreeNode>> so more than one pointer can share it. Box is enough when you own the tree yourself, and it is the clearer way to learn. In all three languages the shape is the same. A node, plus its children, plus a way to say “there is no child here”.
How do you recognise a tree problem?
Read the story first, not the data structure name. Tree problems talk about hierarchy and about a single starting point.
- The input is a
root, or a node withleftandrightchildren. - The wording mentions a parent and a child, a folder, a manager, or another hierarchy.
- You are asked about all nodes, a path from the root, a root-to-leaf path, or a subtree.
- There are no cycles. Each child has one parent, so you can walk down without a visited set.
- The drawing has one start at the top and branches only downward.
If the input is a list of edges, if two nodes can reach each other in more than one way, or if the problem mentions cycles, neighbours, prerequisites or a road map, you are probably looking at a graph. We will pin that down in a moment.
How should you approach a tree problem?
Most tree solutions are a short recursive function. You decide what one node should do, then you trust the same function to handle the smaller trees under it. The recursion helper walks through the call stack if you want a slower look. Here is the habit that works for nearly every tree question.
- Write the base case first. For an empty tree, return the empty answer. That is 0 for a count or a depth,
nullfor a node, ortruefor “is this a valid empty tree?”. For some problems a leaf is a second base case. - Decide what each call returns. A number, a boolean, a node, or a small object. Say it out loud. “This function returns the depth of the tree starting at this node.”
- Ask the children for their answers, then combine them. Maximum depth is 1 plus the larger child depth. A node count is 1 plus the counts of both children. Invert is “swap the inverted children”.
- Pick DFS or BFS. Depth first search goes down one branch, then backtracks. Recursion does this naturally, and a stack does it if you want a loop. Breadth first search goes level by level with a queue, which is the same queue idea as Day 17, Implement Queue using Stacks. Use DFS for depth, height, paths and anything that needs a child answer before the parent finishes. Use BFS for level order, the view from the right side, or the closest leaf.
Time is usually O(n) because you visit each node once. Space is O(h) for recursion, where h is the height, or O(w) for BFS, where w is the widest level. A skinny chain makes h equal to n, so the call stack can get large. The Big O helper explains why that stack still counts as memory.
How does a maximum depth walk work, step by step?
Take a small tree, the same shape that LeetCode 104 Maximum Depth of Binary Tree uses in its examples, and ask for the maximum depth using the LeetCode rule, which counts nodes.
3
/ \
9 20
/ \
15 7
The function is one idea. If the node is missing, the depth is 0. Otherwise the depth is 1 plus the larger of the left depth and the right depth. Watch it on this tree, starting at the bottom because those answers come back first.
max_depth(None)returns 0. That is the base case, and it covers the missing children of 9, 15 and 7.max_depth(15)is 1 + max(0, 0) = 1. The same is true for 7 and for 9, because each of those is a leaf.max_depth(20)asks its children, gets 1 and 1, and returns 1 + max(1, 1) = 2.max_depth(3)asks 9 and 20, gets 1 and 2, and returns 1 + max(1, 2) = 3.
So the answer is 3. The longest path is 3 to 20 to 15, or 3 to 20 to 7, and each of those paths has three nodes. If you count edges instead, the height is 2. Same tree, different convention, which is why it is worth saying which one you are using.
Here is that function in all three languages. I ran each version on this tree, on a single node, and on an empty tree before putting it here.
Java
static int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
Python
def max_depth(root):
if root is None:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
Rust
fn max_depth(root: &Option<Box<TreeNode>>) -> i32 {
match root {
None => 0,
Some(node) => 1 + max_depth(&node.left).max(max_depth(&node.right)),
}
}
Counting nodes is the same pattern with a plus instead of a max. You return 1 + count(left) + count(right), and the empty tree returns 0. Once you can write both of those, you can write a surprising number of tree problems by changing only the combination step.
What mistakes do people make on tree problems?
- Forgetting the empty tree base case, then crashing when a child is missing.
- Mixing up height in edges with LeetCode depth in nodes, and returning 2 when the judge wants 3.
- Writing the recursive calls but ignoring what they return, or returning nothing when the caller needs a number.
- Swapping or overwriting a child before saving the other one. Invert Binary Tree is the classic place this shows up.
- Assuming the tree is balanced. A long chain can overflow a recursive call stack in Python, whose default limit is 1,000 frames. An iterative BFS walk keeps its queue on the heap and does not mind.
- Using a visited set on a plain tree, which is harmless but usually unnecessary, or forgetting a visited set on a graph, which can loop forever.
- Treating every binary tree as a BST. The left and right rule only holds when the problem says it is a search tree.
What is a graph, and how is it different from a tree?
A graph is a set of nodes, also called vertices, joined by edges. That sentence also describes a tree. The difference is what the edges are allowed to do.

- A tree is a special graph. It is connected, it has no cycles, and it has exactly one path between any two nodes. If it has n nodes, it has n − 1 edges. You can pick a root and hang the rest downward.
- A general graph can have cycles. Your friend can be a friend of your other friend, so the links form a loop. If you walk without remembering where you have been, you never stop.
- Edges can be undirected or directed. A two-way road is undirected. A one-way follow on a social app, or a course that must come before another course, is directed.
- Edges can carry a weight. A map edge might store distance or travel time. A tree problem usually has no weights at all.
- A graph may have several components. Not every node can reach every other node, and there may be no single root.
Cycle detection itself already showed up on linked lists in Day 20, Linked List Cycle. A list with a loop is a tiny directed graph. Trees do not have that loop, which is why a tree walk can be simpler.
How do you store a graph?
The usual interview choice is an adjacency list. Each node keeps a list of the nodes it can reach in one step. For an undirected graph you add the edge both ways. The picture above, if we keep the tree on the left as a graph, would store A with B and C, B with A and D, and so on. Here is a small cyclic graph in all three languages.
Java
Map<String, List<String>> graph = new HashMap<>();
graph.put("A", List.of("B", "C"));
graph.put("B", List.of("A", "D"));
graph.put("C", List.of("A"));
graph.put("D", List.of("B"));
Python
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A"],
"D": ["B"],
}
Rust
let mut graph: HashMap<&str, Vec<&str>> = HashMap::new();
graph.insert("A", vec!["B", "C"]);
graph.insert("B", vec!["A", "D"]);
graph.insert("C", vec!["A"]);
graph.insert("D", vec!["B"]);
An adjacency matrix is a V by V grid that stores whether each pair is connected. It answers “is there an edge from a to b?” in O(1), but it costs O(V²) memory, so it is the wrong default for a sparse graph. Most interview graphs are sparse, which is why the list is the one to reach for. Walks are still BFS with a queue or DFS with recursion or a stack, plus a visited set. Time is O(V + E) when you store the graph as a list.
How do you recognise a graph problem?
- The input is n nodes and a list of edges, or a grid where some cells are connected to their neighbours.
- The wording mentions neighbours, connections, roads, friends, prerequisites, dependencies or a network.
- You are asked for a shortest path, a cycle, connected parts, or a valid order of tasks.
- There may be more than one way to go from one node to another, so you must remember what you have already visited.
A quick check helps. If you can draw the input as a hierarchy with one root and no loops, treat it as a tree. If you cannot, treat it as a graph and keep a visited set.
Where do trees show up in real life?
This is the part that makes the structure click, because you have already lived inside these examples.
- File systems. A drive has one root folder. Every file and folder has one parent. That is why an n-ary tree is the natural model, and why a path like
/home/box/notes.mdis just a walk from the root down to a leaf. - Org charts. A CEO has managers, and each manager has a team. Questions like “who reports up to this person?” or “how many people are in this department?” are subtree questions.
- HTML DOM. A web page is a tree of elements. A
divcontains headings and buttons, and the browser walks that tree to draw the page or to find an element. - Database indexes. A BST, or more often a B-tree, keeps keys in order so a lookup can throw away half of the remaining keys at every step. That is why an index makes a search fast as the table grows.
- Autocomplete. A trie, which is a tree of letters, shares prefixes so that typing “ban” can jump straight to “banana” and “band”. The cheat sheet has a short visual of this if you want to see it.
- JSON and config files. Nested objects are trees. A settings file with sections inside sections is the same parent and child idea, stored as text.
- Family trees. The usual drawing from one ancestor is a tree. Real ancestry can be more tangled, but the chart you grew up with is the right mental model.
- Git history. A straight line of commits looks like a skinny tree. When two branches merge, a commit has more than one parent, and the history becomes a directed acyclic graph rather than a pure tree.
Where do graphs show up in real life?
- Maps and GPS. Intersections are nodes, roads are edges, and the travel time is a weight. Finding a route is a shortest path problem on a weighted graph.
- Social networks. People are nodes, and a friendship or a follow is an edge. Your two friends can also be friends with each other, which creates a cycle, so this cannot be a tree.
- Recommendations. Users, videos or products are connected when they are similar or often used together. A walk through that graph is one way a “you might also like” list is built.
- Course or package dependencies. If course B requires course A, that is a directed edge from A to B. The valid study order is a topological order of that graph. Package managers solve the same problem when they install libraries.
- Internet routing. Routers and links form a huge graph. Packets hop along edges, and routing protocols keep choosing good paths as links appear and disappear.
Notice the pattern. Use a tree when there is a clear hierarchy and a single parent. Use a graph when relationships can go both ways, form loops, or carry a cost.
How will this helper fit the rest of the series?
The DSA series hub is the home page for every daily problem. Days 1 to 25 are already live, through arrays, hashing, two pointers, sliding windows, stacks, queues, linked lists and binary search. The trees section opens with Invert Binary Tree, where you swap every left and right child, and continues with Maximum Depth of a Binary Tree, which is the walk we just did. Both will make more sense if you can already picture a root, a leaf and a recursive base case.
When you want practice that prepares the ground, start with Reverse Linked List for pointer rewiring, Implement Queue using Stacks for the queue that BFS uses, Valid Parentheses for a stack that behaves like a call stack, Linked List Cycle for a first look at cycles, and Binary Search for the halving idea that comes back in a BST. Keep the Data Structures Cheat Sheet and the Big O helper nearby, and use the recursion helper if you want to watch a call stack unwind.
Read this once. Then, on the next tree problem you see, name the root, write the base case, and decide what one call should return, before you type anything else.
Frequently asked questions
What is a tree in data structures?
A tree is a set of nodes connected by edges, starting from one root and growing downward, with no cycles. Each child has a single parent. Folders on a disk and a family tree drawn from one ancestor are everyday examples.
What is the difference between a tree and a graph?
A tree is a special graph with no cycles and exactly one path between any two nodes. A general graph can have cycles, directed or weighted edges, several components, and more than one path between the same two nodes.
How do you identify a tree problem in an interview?
Look for a root, parent and child language, a path from the root, a subtree, or a hierarchy with no loops. If the input is a list of edges, mentions neighbours or prerequisites, or can contain cycles, treat it as a graph.
Should I use DFS or BFS on a tree?
Use DFS, usually as recursion, when you need a result from the children before you finish the parent, such as depth, height or a path. Use BFS with a queue when you care about levels, the nearest leaf, or a left-to-right view of each level.
What is the difference between height and depth of a tree?
Depth describes how far a node is from the root. Height describes the longest path down from a node, often from the root. Textbooks usually count edges. LeetCode maximum depth counts nodes, so a single-node tree has depth 1 there and height 0 in the edge convention.





