Quick revision
The short answer
The height of a binary tree is a tree recursion problem, because the answer for a tree is built from the answers for its two subtrees. The height is 1 plus the larger of the two subtree heights, and an empty tree has height 0, which gives a two-line method that runs in O(n) time with O(h) stack space. For very deep trees, counting levels with a queue gives the same answer without recursion.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Probe each depth from the root | O(n * h), O(n^2) for a chain | O(h) stack |
| Recursion, 1 + max of the subtree heights | O(n) | O(h) stack |
| Level order with a queue, counting levels | O(n) | O(w) queue |
What to remember
We measured the height of a binary tree by letting each node ask its two subtrees for their heights and adding one for itself, with an empty tree answering 0. Every node is visited once, so it takes O(n) time, with O(h) stack space for the waiting calls, and counting levels with a queue avoids recursion on very deep trees. The clue to remember is a property of a whole tree that can be built from the same property of its subtrees: write one recursive method, answer null directly, and combine on the way back up.
1What the height of a tree means, told with a family tree
Think of a family tree drawn on paper, with a grandmother at the top, her children on the line below, and their children below that. If someone asks how many generations the tree spans, you find the longest line of descent, from the grandmother down to the youngest person at the bottom, and count the people on it. The height of a binary tree is exactly that count.
A binary tree is made of nodes. Each node holds a value and has at most two children, called left and right; binary means two. The node at the top, which has no parent, is the root. A node with no children is a leaf. The height is the number of nodes on the longest path from the root down to a leaf. Our method receives the root and must return that number.
We keep one example for the whole article. The root is 3. Its left child is 9, a leaf. Its right child is 20, and 20 has two leaf children, 15 and 7. Let us measure by hand. The path 3, 9 has two nodes. The paths 3, 20, 15 and 3, 20, 7 have three nodes each. The longest is three nodes, so the height is 3.
Root 3, with 9 on the left and 20 on the right; 20 has the children 15 and 7. The marked path has three nodes.
- root
- 3
- leaves
- 9, 15, 7
- height
- 3
1The longest path from the root down to a leaf is 3, 20, 15 (3, 20, 7 is just as long). It has three nodes, so the height is 3.
What to assume
- Do we count nodes or edges?
- Some books count the links between nodes, called edges, which would give 2 for our tree. Both are fine as long as we say which; we count nodes, so a single node has height 1 and an empty tree, a null root, has height 0.
- Is the tree balanced, with both sides about equally tall?
- Not necessarily; it may be skewed, every node having only one child, like a chain.
- How large can it be?
- Large enough that the depth of recursion may matter.
Trees can feel frightening at first, because they branch, and it is hard to see how a program keeps track of all the branches. The problem is smaller than it looks. We will see that the whole solution is two lines, because each node only has to ask its two children one question and add one.
A careful candidate asks a few questions first. Do we count nodes or edges? Some books count the links between nodes, called edges, which would give 2 for our tree. Both are fine as long as we say which; we count nodes, so a single node has height 1 and an empty tree, a null root, has height 0. Is the tree balanced, with both sides about equally tall? Not necessarily; it may be skewed, every node having only one child, like a chain. How large can it be? Large enough that the depth of recursion may matter, which we come back to.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a tree recursion problem
When a beginner reads this question, the natural first thought is to walk every path from the root to a leaf, measure each one, and keep the longest. That thought is right in spirit, but writing it with loops is awkward, because a tree has no single next node to step to. So let us read the question slowly and look for clues.
The first clue is the words binary tree. Every node in a binary tree is the root of a smaller binary tree, made of itself and everything below it. That smaller tree is called a subtree. In our example, node 20 with 15 and 7 is a subtree, and so is the leaf 9 on its own. So a tree is built from smaller trees of the same kind.
The second clue is the word height, a property of the whole tree. Ask how the height of the whole tree relates to the heights of its subtrees. The longest path starts at the root and then goes down into either the left subtree or the right one. So the height of the tree is one more than the taller of its two subtrees. A property of the whole that can be built from the same property of the parts is the strongest clue of all.
Together these clues point to the trees family, and to tree recursion. Recursion means a method that calls itself on a smaller version of the same problem, the way the grandmother could ask each of her children how many generations their own family spans, and then add one for herself. Every call must eventually reach a case small enough to answer directly, called the base case. The general rule to carry away is this. When a tree property can be computed at a node from the same property of its children, write one recursive method, answer the empty tree directly, and combine the children's answers on the way back up.
Some patterns look similar but do not fit as well. Breadth-first search, which visits the tree level by level using a queue, also works, because the height is the number of levels, and it is the answer when recursion is risky. Dynamic programming also combines answers to smaller problems, but in a tree each subtree is visited only once, so there is nothing to remember and reuse.
3The honest first attempt, probing one depth at a time
The brute force, the honest first idea that avoids thinking about the answer recursively, asks a simpler yes-or-no question again and again. Is there any node at depth 1? At depth 2? At depth 3? The depth of a node is its position counted from the root, with the root at depth 1. The first depth that has no node tells us the height, one less than it.
Each frame is one probe. Marked nodes are the ones that probe visits; the root is visited every time.
- probe depth
- 1
- found a node
- yes
- this probe
- 1 visits
- so far
- 1 visits
1Probe 1 asks whether depth 1 has a node. It visits only the root, 3, and says yes.
- probe depth
- 2
- found a node
- yes
- this probe
- 2 visits
- so far
- 3 visits
2Probe 2 starts from the root again. It walks 3 and then 9, which sits at depth 2, and says yes.
- probe depth
- 3
- found a node
- yes
- this probe
- 4 visits
- so far
- 7 visits
3Probe 3 starts from the root once more. It walks 3, 9, then 20 and 15, which is at depth 3, and says yes.
- probe depth
- 4
- found a node
- no
- this probe
- 5 visits
- so far
- 12 visits
4Probe 4 walks all five nodes and finds nothing at depth 4, so the height is 3. Twelve visits for five nodes.
Let us count on the example; the picture shows each probe. Probe 1 visits only the root and says yes. Probe 2 starts at the root again and reaches 9, two visits. Probe 3 starts at the root once more and walks 3, 9, 20 and 15, four visits. Probe 4 walks all five nodes and finds nothing, so the height is 3. That is 12 visits to measure a tree of 5 nodes.
In general there is one probe per level, and each probe may walk every node above that level. For a skewed tree of n nodes, a chain, probe d walks d nodes, so the total is about 1 + 2 + ... + n, roughly n times n over 2. That grows like n squared, written O(n^2). For 10,000 nodes in a chain, about 50 million visits.
So where is the waste? The top of the tree is walked again for every level. The root was visited four times and node 9 three times, and each probe forgot what it learned about the subtrees below. So let us ask the question that leads further. If each subtree could simply tell us its own height, once, could the parent combine those answers without walking anything twice?
4Getting to the recursive answer, one observation at a time
Suppose a helpful friend tells us the height of the left subtree and the height of the right subtree. In our example, the left subtree, just 9, has height 1, and the right subtree, 20 with 15 and 7, has height 2. The longest path from the root goes through the root itself and then down into whichever subtree is taller. So the height is 1 for the root plus the larger of the two, 1 + max(1, 2) = 3. Written as a rule, height(node) = 1 + max(height(node.left), height(node.right)).
But who is the helpful friend? The same method, called on the smaller tree. That is recursion: height asks height for the answer on each subtree, and those calls ask again on their subtrees, just as each person in the family tree asks their own children.
Now comes the question every beginner asks. If every call asks two more calls, how does it ever stop? It stops at the base case. When a call reaches a missing child, the node is null, an empty tree, and the height of an empty tree is 0. That call answers at once, without asking anyone. Because the trees get smaller with every call, every chain of calls reaches a null eventually.
Why null and not the leaf as the base case? Let us see what null gives a leaf. Node 9 asks its two children, both null, which return 0 and 0, so 9 returns 1 + max(0, 0) = 1, correct, without any special code for leaves. A beginner often writes a separate check for leaves as well, which is harmless but unneeded, or forgets the null check altogether and gets a NullPointerException on the first leaf.
While a call waits for its children, Java keeps it on the call stack, a pile of unfinished method calls where the newest is on top. When height(15) is running, height(20) and height(3) wait below it. The stack is as deep as the path we are on, which is the height h. For a balanced tree of a million nodes that is about 20 calls, harmless. For a skewed chain of 100,000 nodes it is 100,000 calls, which can overflow Java's default stack with a StackOverflowError. For that case we count levels instead, with a queue, in heightIterative.
Why is the recursion correct? For an empty tree, 0 is correct by definition. For any other tree, if the calls on the two subtrees return their correct heights, then 1 plus the larger is correct, because the longest path must go through the root into one of them. Since the subtrees are smaller, this argument works from the leaves upwards for every node.
5Watching the heights come back up the example tree
The picture plays height on our tree, one frame per call starting or returning, in the order the Java method ran. The node whose call is running is marked as now, the calls waiting above it on the call stack are marked as compared, and finished nodes are marked as done. The panel shows the call stack and every height returned so far.
Watch the direction of the work. The calls go down first, but the answers are worked out from the bottom up.
The running call is marked as now and the calls waiting on the stack as compared. Heights travel back up: 9 returns 1, 15 and 7 return 1, 20 returns 2, 3 returns 3.
- call stack
- 3
- returned
- none yet
1
height(3)starts at the root. It cannot answer yet, because it needs the heights of both its subtrees, so it first callsheight(9).- call stack
- 3 -> 9
- returned
- none yet
2
height(9)runs whileheight(3)waits on the call stack. Node 9 has no children, so both of its calls get null and return 0 at once.- call stack
- 3 -> 9
- returned
- 9:1
- this call
- 1 + max(0, 0) = 1
3
height(9)returns 1 +max(0, 0)= 1. Node 9 is finished, andheight(3)now knows its left subtree is 1 tall.- call stack
- 3 -> 20
- returned
- 9:1
4
height(3)now callsheight(20)for its right side. Node 20 has two children, so it must wait for both of them in turn.- call stack
- 3 -> 20 -> 15
- returned
- 9:1
5
height(15)runs, with 3 and 20 waiting above it. Its children are null, so both calls return 0.- call stack
- 3 -> 20 -> 15
- returned
- 9:1, 15:1
- this call
- 1 + max(0, 0) = 1
6
height(15)returns 1 +max(0, 0)= 1 to node 20, which now callsheight(7)for its right child.- call stack
- 3 -> 20 -> 7
- returned
- 9:1, 15:1
7
height(7)runs. It is a leaf as well, so both its calls hit null and return 0.- call stack
- 3 -> 20 -> 7
- returned
- 9:1, 15:1, 7:1
- this call
- 1 + max(0, 0) = 1
8
height(7)returns 1. Node 20 now has both answers, 1 from 15 and 1 from 7.- call stack
- 3 -> 20
- returned
- 9:1, 15:1, 7:1, 20:2
- this call
- 1 + max(1, 1) = 2
9
height(20)returns 1 +max(1, 1)= 2. Node 3 now has both answers, 1 from the left and 2 from the right.- call stack
- 3
- returned
- 9:1, 15:1, 7:1, 20:2, 3:3
- this call
- 1 + max(1, 2) = 3
10
height(3)returns 1 +max(1, 2)= 3, the height of the whole tree. Each node was visited exactly once.
Let us read the important frames back. In the first frame height(3) cannot answer, so it waits and calls height(9). Node 9 is a leaf, so its two calls on null return 0 straight away, and in the third frame it returns 1.
Then the root turns to its right child. height(20) calls height(15), which returns 1, and then height(7), which returns 1. Look at the call stack in those frames: it never holds more than three calls, the height of the tree.
In the ninth frame node 20 has both answers and returns 1 + max(1, 1) = 2. In the last frame the root combines 1 from the left and 2 from the right and returns 3. Each node was visited once, five visits in all against the twelve of the probing method.
6The complete Java program
Here is the full program. A Java record keeps the Node class short; a record is a small class whose fields are fixed when it is built, read with methods such as left(). There are two versions, the recursive height and the level-by-level heightIterative. main runs both on the example, checks the empty tree and a single node, and builds a skewed chain of 100,000 nodes for the iterative version.
Let us read height in the order it runs. The first line is the base case: an empty tree returns 0. Every other call goes to the second line, which calls height on the left child, then on the right child, takes the larger with Math.max and adds 1 for the node itself. That one line is the rule we reasoned out.
Now heightIterative. It puts the root in a queue, a line where the first to join is the first served, and counts levels. Each time round the outer loop, the queue holds exactly one level of the tree, so we add one to levels. The inner for loop takes out exactly that many nodes, reading queue.size() once at the start, and puts their children in the queue for the next level. Reading size() inside the loop condition instead would be a mistake, because the children being added would mix two levels together.
In main, both versions print 3 for our tree, the empty tree prints 0 and a single node prints 1. The chain of 100,000 nodes, each one the left child of the next, prints 100000 from the iterative version. We do not call the recursive version on it, because that is exactly the input that may overflow the stack.
7How much it costs, and the cases at the edges
Let us count on the example first. The recursive version made one call per node, five in all, plus one quick call for each of the six null children, and each call did a constant amount of work. For n nodes that is about 2n + 1 calls, so the time is O(n). The iterative version also handles each node once, O(n) too. We cannot do better, because the deepest leaf could be anywhere, so every node must be looked at.
The space is different for the two. The recursion keeps one waiting call per node on the current path, so it uses O(h) stack space, where h is the height: O(log n) for a balanced tree and O(n) for a chain. The queue holds at most one level at a time, so heightIterative uses O(w) space, where w is the width of the widest level, up to about n / 2 for a full tree.
| Approach | Time | Extra space |
|---|---|---|
| Probe each depth from the root | O(n * h), O(n^2) for a chain | O(h) stack |
| Recursion, 1 + max of the subtree heights | O(n) | O(h) stack |
| Level order with a queue, counting levels | O(n) | O(w) queue |
The edge cases need no special code. An empty tree returns 0 from the base case. A single node returns 1 + max(0, 0) = 1. A skewed tree is handled correctly by both versions, but only the iterative one is safe when it is very deep. And if the interviewer counts edges instead of nodes, every answer is one less, and the base case becomes -1 for an empty tree.
8Follow-up questions
How would you check whether a tree is height balanced?
A tree is balanced when, at every node, the heights of the two subtrees differ by at most 1. Calling height separately at every node repeats the same work again and again, up to O(n^2) on a chain. Instead, we compute heights bottom up once, in the same kind of recursive method, and return a special value such as -1 as soon as any subtree is unbalanced or the two heights differ by more than 1. A parent that receives -1 passes it straight up. The whole check is then O(n).
How would you find the minimum depth instead?
The minimum depth is the number of nodes on the shortest path from the root to a leaf. The recursion needs care, because a missing child is not a leaf. If a node has only a right child, taking the minimum with the empty left side would give 1 + 0, which is wrong; we must take the right side instead. Breadth-first search is even more natural here, because it visits the tree level by level and can stop at the first leaf it meets, which is on the shallowest level.
What is the difference between height and depth?
Depth belongs to a node and is measured from the top: how many nodes lie on the path from the root down to it, so the root has depth 1 in our counting. Height belongs to a tree or subtree and is measured downwards: the number of nodes on the longest path from its root to a leaf. The height of the whole tree equals the largest depth of any node, which is why the probing method works.
9Conclusion
We measured the height of a binary tree by letting each node ask its two subtrees for their heights and adding one for itself, with an empty tree answering 0. Every node is visited once, so it takes O(n) time, with O(h) stack space for the waiting calls, and counting levels with a queue avoids recursion on very deep trees. The clue to remember is a property of a whole tree that can be built from the same property of its subtrees: write one recursive method, answer null directly, and combine on the way back up.
Open with
Let me fix the convention first. I count nodes, so an empty tree has height 0 and a single node has height 1. I would also ask how deep the tree can be, because that decides whether recursion is safe.
Then, if they want more
A brute force could ask depth by depth whether any node exists there, but each probe walks the top of the tree again, which is O(n squared) on a skewed tree. The height has a natural recursive structure: the longest path goes through the root and then into the taller subtree.
So height of a node is one plus the maximum of the heights of its left and right children, and height of null is 0. That base case also makes a leaf come out as 1 without special code.
Every node is visited once, so the time is O(n), and the recursion uses O(h) stack space, log n for a balanced tree but n for a chain.
If the tree can be very deep, I would switch to a level-order traversal with a queue, counting levels by draining one level at a time, which is O(n) time and O(w) space for the widest level, with no risk of stack overflow.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 36 times in that collection. How it is counted
- Official documentation
- ArrayDeque (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Compute the height of a binary tree.": https://scrivio-interview-library.netlify.app/data-structures/solutions/compute-the-height-of-a-binary-tree-eaea4c/
Coding patterns, question 10 of 15 Back to the path
More trees questions