Depth counts edges from root to a node (top-down). Root depth = 0.
Height counts edges from a node down to the farthest leaf (bottom-up). Leaf height = 0.
Empty tree height by convention is -1, making leaf height correctly 0.
Height calculation visits every node in subtree: O(n). Depth search stops at node: O(d).
Production pitfall: misidentifying height as number of nodes breaks balancing algorithms.
Confusing direction (depth vs height) is the most common interview slip.
Plain-English First
Picture a family tree hanging on a wall. The great-grandparent at the top is the root. The depth of any person on that tree is simply how many generations down they sit from the top — grandchildren are deeper than children. The height of the whole tree is just how many generations tall it is from top to bottom. That's it. Height and depth are just ways of measuring position and size inside a tree structure.
Binary trees show up everywhere in software — from how your operating system organises files, to how databases run lightning-fast searches, to how compilers parse your code. Before you can work with any of those systems, you need to be able to answer two deceptively simple questions: 'How deep is this node?' and 'How tall is this tree?' Those two questions have precise answers, and knowing them unlocks a huge chunk of tree-related problem solving.
The confusion beginners run into is that height and depth sound like the same thing — and in everyday English they almost are. But in binary trees they measure opposite directions. Depth is measured top-down (root toward leaves). Height is measured bottom-up (leaves toward root). Mix them up and your algorithms silently produce wrong answers, which is one of the most frustrating kinds of bug to track down.
By the end of this article you'll be able to define height and depth precisely, calculate both by hand on any tree you draw, write a clean recursive Java implementation from memory, and explain the difference confidently in an interview. We'll build everything from zero — no prior tree knowledge assumed.
Height and Depth of a Binary Tree — Plain English and Algorithm
Height of a node: the number of edges on the longest path from that node to a leaf. Leaf height = 0. Height of a tree: height of the root. Depth of a node: number of edges from the root to that node. Root depth = 0.
Algorithm — compute height of a tree recursively: 1. If node is None: return -1 (empty tree has height -1). 2. left_height = height(node.left). 3. right_height = height(node.right). 4. Return 1 + max(left_height, right_height).
A balanced tree has height O(log n). A degenerate (skewed) tree has height O(n).
Production Insight
Misidentifying height as node count instead of edge count is a common production bug.
It silently unbalances AVL and Red-Black trees, turning O(log n) into O(n).
Rule: always define height with null = -1 and verify with a single-node tree.
Key Takeaway
Height is measured bottom-up from leaf to root.
Leaf height = 0, empty tree height = -1.
Confuse it with node count and your tree algorithms will silently degrade.
What Is a Binary Tree? (Building the Foundation)
Before we measure anything, let's make sure we agree on what we're measuring.
A binary tree is a collection of nodes where each node stores a value and can have at most two children — a left child and a right child. The topmost node (with no parent) is called the root. Nodes with no children at all are called leaf nodes.
Think of it like a tournament bracket. There's one champion at the top (the root). That champion beat two finalists (left and right children). Each finalist beat two semi-finalists, and so on, all the way down to the first-round players who never won a match (the leaves).
Here's the tree we'll use throughout this entire article. Keep this picture in your head:
Every measurement we make in the following sections uses exactly this tree. No surprises.
BinaryTreeNode.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// A single node in a binary tree.// Each node holds a value and optional references to a left and right child.publicclassBinaryTreeNode {
int value; // The data stored at this nodeBinaryTreeNode leftChild; // Reference to the left subtree (null if none)BinaryTreeNode rightChild; // Reference to the right subtree (null if none)// Constructor: create a new node with a value and no children yetpublicBinaryTreeNode(int value) {
this.value = value;
this.leftChild = null;
this.rightChild = null;
}
// Helper method so we can print a node nicely (useful for debugging)
@OverridepublicStringtoString() {
return"Node(" + value + ")";
}
// --- Build the example tree from the article ---publicstaticBinaryTreeNodebuildExampleTree() {
// 10// / \// 5 20// / \ \// 3 7 25// /// 1BinaryTreeNode root = newBinaryTreeNode(10);
BinaryTreeNode node5 = newBinaryTreeNode(5);
BinaryTreeNode node20 = newBinaryTreeNode(20);
BinaryTreeNode node3 = newBinaryTreeNode(3);
BinaryTreeNode node7 = newBinaryTreeNode(7);
BinaryTreeNode node25 = newBinaryTreeNode(25);
BinaryTreeNode node1 = newBinaryTreeNode(1);
root.leftChild = node5; // 10's left child is 5
root.rightChild = node20; // 10's right child is 20
node5.leftChild = node3; // 5's left child is 3
node5.rightChild = node7; // 5's right child is 7
node20.rightChild = node25; // 20's right child is 25
node3.leftChild = node1; // 3's left child is 1
return root; // hand back the top of the tree
}
publicstaticvoidmain(String[] args) {
BinaryTreeNode root = buildExampleTree();
System.out.println("Root node: " + root);
System.out.println("Root's left child: " + root.leftChild);
System.out.println("Root's right child: " + root.rightChild);
System.out.println("Deepest leaf: " + root.leftChild.leftChild.leftChild);
}
}
Output
Root node: Node(10)
Root's left child: Node(5)
Root's right child: Node(20)
Deepest leaf: Node(1)
Quick Vocab Check:
Root = top node (no parent). Leaf = bottom node (no children). Edge = the line connecting a parent to a child. These three words are all you need for the next two sections.
Production Insight
In real codebases, the tree structure is often built from serialised data.
A common bug is that the right child of node 20 is stored as null in the database, causing height calculation to miss entire subtrees.
Always validate that all nodes are linked correctly before trusting height/depth results.
Key Takeaway
Binary trees have one root, two children per node, and leaves at the bottom.
Every measurement starts from this structure.
Know your tree shape before you start measuring.
Depth of a Node — How Far Down Are You?
The depth of a node is the number of edges (connections) you travel from the root to reach that node.
The root itself has depth 0 — you're already there, no travel needed. Its direct children have depth 1. Their children have depth 2, and so on.
Using our example tree
Node 10 (root): depth 0
Node 5, Node 20: depth 1
Node 3, Node 7, Node 25: depth 2
Node 1: depth 3
The rule is beautifully simple: depth(node) = depth(parent) + 1.
To calculate depth in code, you walk down from the root, counting each step until you find the target node. This is naturally a recursive or iterative search — you don't know the depth until you've found the node.
One important mental model: depth is a property of a specific node relative to the root. Two nodes at the same level always have the same depth. You can't talk about 'the depth of the tree' — that would be the height (coming up next).
NodeDepthFinder.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
publicclassNodeDepthFinder {
// Finds the depth of the node containing 'targetValue' in the tree.// 'currentNode' — the node we are currently visiting// 'targetValue' — the value we are searching for// 'currentDepth' — how many edges we have already travelled from the root//// Returns -1 if the value is not found in the tree.publicstaticintfindDepth(BinaryTreeNode currentNode, int targetValue, int currentDepth) {
// Base case 1: we fell off the edge of the tree — node doesn't existif (currentNode == null) {
return -1; // signal that we couldn't find the target
}
// Base case 2: we found the target node!if (currentNode.value == targetValue) {
return currentDepth; // the depth is however far we've already travelled
}
// Recursive case: search the left subtree firstint depthInLeftSubtree = findDepth(currentNode.leftChild, targetValue, currentDepth + 1);
// If left subtree found it, no need to check right subtreeif (depthInLeftSubtree != -1) {
return depthInLeftSubtree;
}
// Otherwise, search the right subtreereturnfindDepth(currentNode.rightChild, targetValue, currentDepth + 1);
}
publicstaticvoidmain(String[] args) {
BinaryTreeNode root = BinaryTreeNode.buildExampleTree();
// Test every node in our example treeint[] valuesToCheck = {10, 5, 20, 3, 7, 25, 1};
System.out.println("Node Value | Depth");
System.out.println("-----------|------");
for (int value : valuesToCheck) {
// Always start the search from the root at depth 0int depth = findDepth(root, value, 0);
System.out.printf(" %2d | %d%n", value, depth);
}
// What happens when we search for a value that isn't in the tree?int missingDepth = findDepth(root, 99, 0);
System.out.println("\nDepth of missing node (99): " + missingDepth);
}
}
Output
Node Value | Depth
-----------|------
10 | 0
5 | 1
20 | 1
3 | 2
7 | 2
25 | 2
1 | 3
Depth of missing node (99): -1
Interview Gold:
Interviewers love asking 'what does depth of the root equal?' The answer is always 0 — not 1. The root has travelled zero edges to reach itself. Saying '1' is the most common slip-up in interviews.
Production Insight
When implementing a tree for an autocomplete or database index, depth translates directly to query latency.
Each edge traversed is a pointer dereference or a disk read.
Use iterative depth-first search with explicit stack to avoid stack overflow on deep trees in production.
Key Takeaway
Depth is measured from root to node, counting edges.
Root depth = 0, leaf depth varies.
It's a distance metric, not a size metric.
Height of a Node and Tree — How Tall Are You?
Height flips the direction. Where depth asks 'how far from the top?', height asks 'how far to the bottom?'
The height of a node is the number of edges on the longest path from that node down to any leaf below it.
Leaf nodes have height 0 — there are no edges below them, nowhere left to go. Their parents have height 1. The root's height equals the height of the entire tree.
The recursive formula is elegant: height(node) = 1 + max(height(leftChild), height(rightChild)).
You pick the taller of the two subtrees and add 1 for the edge connecting you to it. Recursion bottoms out at null nodes, which we define as having height -1 (so a single leaf correctly gets height 0).
TreeHeightCalculator.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
publicclassTreeHeightCalculator {
// Calculates the height of any given node.// Height = number of edges on the LONGEST path from this node to a leaf below it.//// Key insight: a null node has height -1 by convention.// This makes a single leaf node correctly return height 0:// height(leaf) = 1 + max(-1, -1) = 1 + (-1) = 0 ✓publicstaticintcalculateHeight(BinaryTreeNode node) {
// Base case: null means we've gone past a leaf — define as -1if (node == null) {
return -1;
}
// Recursively find the height of the left subtreeint leftSubtreeHeight = calculateHeight(node.leftChild);
// Recursively find the height of the right subtreeint rightSubtreeHeight = calculateHeight(node.rightChild);
// This node's height = 1 edge to the taller child + that child's heightint tallestChildHeight = Math.max(leftSubtreeHeight, rightSubtreeHeight);
return1 + tallestChildHeight;
}
publicstaticvoidmain(String[] args) {
BinaryTreeNode root = BinaryTreeNode.buildExampleTree();
// Height of the whole tree (measured from root)int treeHeight = calculateHeight(root);
System.out.println("Height of the entire tree: " + treeHeight);
// Individual node heightsSystem.out.println("\nNode Value | Height");
System.out.println("-----------|-------");
System.out.printf(" %2d | %d (root — tallest point)%n", root.value, calculateHeight(root));
System.out.printf(" %2d | %d (has subtree of depth 2)%n", root.leftChild.value, calculateHeight(root.leftChild));
System.out.printf(" %2d | %d (only one child below it)%n",root.rightChild.value, calculateHeight(root.rightChild));
System.out.printf(" %2d | %d (one leaf child below it)%n",root.leftChild.leftChild.value, calculateHeight(root.leftChild.leftChild));
System.out.printf(" %2d | %d (leaf — no children)%n", root.leftChild.leftChild.leftChild.value, calculateHeight(root.leftChild.leftChild.leftChild));
System.out.printf(" %2d | %d (leaf — no children)%n", root.leftChild.rightChild.value, calculateHeight(root.leftChild.rightChild));
System.out.printf(" %2d | %d (leaf — no children)%n", root.rightChild.rightChild.value, calculateHeight(root.rightChild.rightChild));
// Edge case: what is the height of an empty tree?int emptyTreeHeight = calculateHeight(null);
System.out.println("\nHeight of an empty tree (null root): " + emptyTreeHeight);
}
}
Output
Height of the entire tree: 3
Node Value | Height
-----------|-------
10 | 3 (root — tallest point)
5 | 2 (has subtree of depth 2)
20 | 1 (only one child below it)
3 | 1 (one leaf child below it)
1 | 0 (leaf — no children)
7 | 0 (leaf — no children)
25 | 0 (leaf — no children)
Height of an empty tree (null root): -1
Watch Out:
Some textbooks define height as the number of nodes on the longest path (not edges). That makes a single-node tree height 1 instead of 0. Always clarify which definition an interviewer is using before you start coding — it changes your base case from -1 to 0.
Production Insight
Recursion depth in height calculation equals the tree height itself.
For a skewed tree with 10,000 nodes, this means 10,000 stack frames — a guaranteed StackOverflowError in many JVM configurations.
Use an iterative post-order traversal (explicit stack) for production code on unknown data.
Key Takeaway
Height is measured from node to deepest leaf, counting edges.
Leaf height = 0, root height = tree height.
Null returns -1 to make the formula work consistently.
Putting It All Together — One Complete Program
Now let's combine everything into a single runnable file that builds the tree, calculates both depth and height for every node, and prints a clean summary table.
This is the kind of code you'd actually write to verify your understanding before an interview. Running it and seeing the correct numbers builds real confidence — far more than just reading about it.
Notice the relationship between depth and height: for the root, depth is 0 and height is 3. For the deepest leaf (node 1), depth is 3 and height is 0. They're perfectly complementary — they always sum to the height of the tree for nodes on the longest path. That's a neat property worth remembering.
Also notice the time complexity: calculating height for a single node costs O(n) because you visit every node in its subtree. Calculating the depth of a single node costs O(d) where d is its depth — much cheaper if the tree is balanced.
HeightAndDepthDemo.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Complete, self-contained demo.// Builds the example tree and prints a full depth + height table.publicclassHeightAndDepthDemo {
// ── Node Definition ───────────────────────────────────────────staticclassTreeNode {
int value;
TreeNode left, right;
TreeNode(int value) {
this.value = value;
}
}
// ── Tree Builder ───────────────────────────────────────────────// 10// / \// 5 20// / \ \// 3 7 25// /// 1staticTreeNodebuildTree() {
TreeNode root = newTreeNode(10);
root.left = newTreeNode(5);
root.right = newTreeNode(20);
root.left.left = newTreeNode(3);
root.left.right = newTreeNode(7);
root.right.right= newTreeNode(25);
root.left.left.left = newTreeNode(1);
return root;
}
// ── Height Calculation ─────────────────────────────────────────// Returns -1 for null (so a leaf correctly gets height 0)staticintheight(TreeNode node) {
if (node == null) return -1;
return1 + Math.max(height(node.left), height(node.right));
}
// ── Depth Calculation ──────────────────────────────────────────// Returns -1 if targetValue is not found anywhere in the treestaticintdepth(TreeNode node, int targetValue, int currentDepth) {
if (node == null) return -1; // not foundif (node.value == targetValue) return currentDepth; // found it!int leftResult = depth(node.left, targetValue, currentDepth + 1);
if (leftResult != -1) return leftResult; // found in left subtree
return depth(node.right, targetValue, currentDepth + 1); // try right
}
// ── Main ───────────────────────────────────────────────────────publicstaticvoidmain(String[] args) {
TreeNode root = buildTree();
int treeHeight = height(root);
System.out.println("=== Binary Tree: Height and Depth Summary ===");
System.out.println("Overall tree height: " + treeHeight + " edges");
System.out.println();
System.out.printf("%-12s %-8s %-8s %-10s%n", "Node Value", "Depth", "Height", "Depth+Height");
System.out.println("----------------------------------------------");
// All node values in our treeint[] allValues = {10, 5, 20, 3, 7, 25, 1};
for (int val : allValues) {
int d = depth(root, val, 0); // depth from root
int h = height(findNode(root, val)); // height from this node downSystem.out.printf("%-12d %-8d %-8d %-10d%n", val, d, h, d + h);
}
System.out.println("----------------------------------------------");
System.out.println("Notice: depth + height = " + treeHeight + " for all nodes on the longest path.");
}
// Helper: returns the TreeNode with the given value (simple DFS search)staticTreeNodefindNode(TreeNode node, int targetValue) {
if (node == null) returnnull;
if (node.value == targetValue) return node;
TreeNode leftResult = findNode(node.left, targetValue);
return (leftResult != null) ? leftResult : findNode(node.right, targetValue);
}
}
Output
=== Binary Tree: Height and Depth Summary ===
Overall tree height: 3 edges
Node Value Depth Height Depth+Height
----------------------------------------------
10 0 3 3
5 1 2 3
20 1 1 2
3 2 1 3
7 2 0 2
25 2 0 2
1 3 0 3
----------------------------------------------
Notice: depth + height = 3 for all nodes on the longest path.
Pattern to Remember:
For every node that sits on the tree's longest (deepest) path: depth + height = total tree height. Node 10: 0+3=3. Node 5: 1+2=3. Node 3: 2+1=3. Node 1: 3+0=3. This identity is a quick sanity check you can use to verify your code is correct.
Production Insight
In production, you rarely need per-node depth except for debugging.
Height is used extensively in tree balancing algorithms like AVL and Red-Black.
Always choose the iterative height calculation for large datasets to avoid stack overflow and ensure consistent performance.
Key Takeaway
Height and depth together describe position and size of a node.
For nodes on the longest path: depth + height = tree height.
Master this identity and you'll never confuse the two again.
● Production incidentPOST-MORTEMseverity: high
The AVL Tree That Lost Its Balance — Height Misdefinition Caused O(n) Search
Symptom
API endpoint that looked up user profiles by ID started timing out (5% of requests took >30s). Performance degraded gradually over weeks as new users were added.
Assumption
The team assumed that the height function was returning correct values because it passed unit tests (tests only checked a few small trees, where off-by-one didn't affect balance decisions).
Root cause
The height function in the AVL tree's balanceFactor calculation returned the number of nodes on the longest path instead of edges. For a leaf node it returned 1, for a null child it returned 0. This meant every node's height was off by 1, so the balance factor of perfectly balanced trees showed ±2 instead of ±1, and actually unbalanced trees showed ±1 and were left as-is.
Fix
Changed the base case from if(node == null) return 0; to if(node == null) return -1;. Verified leaf height becomes 0. Re-ran all unit tests with edge case trees containing 1, 2, and 3 nodes. Deployed a hotfix: recalculated heights on the entire tree and rebalanced.
Key lesson
Always define height as edge count with null = -1 for recursive tree algorithms.
Don't trust unit tests that only cover small trees — add a test with a skewed tree to catch off-by-one bugs.
Tree balancing logic is hypersensitive to height definition — a single off-by-one can tank performance silently.
Production debug guideSystematic symptom-to-fix guide for when your tree metrics are off5 entries
Symptom · 01
Height of leaf returns 1 instead of 0
→
Fix
Check the base case in recursive height function. Ensure null node returns -1, not 0.
Symptom · 02
Height of entire tree is one more than expected
→
Fix
Verify you're counting edges, not nodes. If using node count, subtract 1 from final result or adjust base case.
Symptom · 03
Depth of root returns 1 instead of 0
→
Fix
Make sure the initial call passes currentDepth=0. Don't increment before the root check.
Symptom · 04
Depth search returns -1 for existing node
→
Fix
Confirm the algorithm passes the correct target value and returns the accumulated depth when node is found. Check that recursion does not skip a level.
Symptom · 05
Balance checks incorrectly flag unbalanced trees
→
Fix
Verify that height values used in balance factor are consistent: both left and right heights must use the same definition (edges). Check that null children return -1.
★ Quick Debug: Tree Height & DepthFor use when tree metrics don't match expectations while coding on a whiteboard or debugging a tree algorithm.
it counts edges from the root to a specific node. Root always has depth 0.
2
Height measures bottom-up
it counts edges on the longest path from a node down to any leaf below it. Leaf nodes always have height 0.
3
Define null nodes as height -1 in your code
this is the correct base case that makes all other height values work out cleanly without special-casing leaves.
4
The height of the entire tree equals the height of the root node
they are the same measurement. You don't need a separate function for 'tree height'.
5
For any node on the longest path
depth + height = tree height. Use this identity as a code-level sanity check.
Common mistakes to avoid
4 patterns
×
Treating null as height 0 instead of -1
Symptom
Leaf nodes report height 1 instead of 0. A tree with only a root reports height 1 instead of 0. All balance factors shift by 1, making AVL trees seem unbalanced when they are not.
Fix
Return -1 for null in height function: if (node == null) return -1;. Then height(leaf) = 1 + max(-1, -1) = 0.
×
Starting depth at 1 instead of 0
Symptom
Every depth answer is shifted up by 1. Root appears at depth 1, leaf depth becomes 4 instead of 3. Any algorithm using depth as a level index breaks.
Fix
Always initialise currentDepth to 0 when calling findDepth from the root. Never increment before checking the root.
×
Thinking 'height of the tree' is different from height of the root
Symptom
Developers write a separate function for tree height that manually counts levels, often off by one. They then use it in balancing where the height of root is expected.
Fix
The height of the tree is exactly the height of its root node. Call calculateHeight(root) to get the tree height — no separate logic needed.
×
Using a global variable for depth across recursive calls without resetting
Symptom
Depth values become corrupted across different searches because the global variable is not reset between calls. Consecutive depth queries give wrong results.
Fix
Pass depth as a parameter (currentDepth) so each recursive call has its own copy. Avoid static or global counters for depth computations.
INTERVIEW PREP · PRACTICE MODE
Interview Questions on This Topic
Q01JUNIOR
What is the difference between the height and depth of a node in a binar...
Q02SENIOR
Write a recursive function to find the height of a binary tree. What is ...
Q03SENIOR
A balanced binary tree has n nodes. What is the relationship between its...
Q04SENIOR
Given a binary tree, implement an iterative method to find its maximum d...
Q01 of 04JUNIOR
What is the difference between the height and depth of a node in a binary tree? Can you give an example using a tree you draw on the whiteboard?
ANSWER
Depth measures the number of edges from the root down to the node. Root depth = 0. Height measures the number of edges from the node down to the farthest leaf. Leaf height = 0. For the root of a tree with height 3, depth = 0, height = 3. For a leaf at depth 3, height = 0. On the longest path, depth + height equals the tree height.
Q02 of 04SENIOR
Write a recursive function to find the height of a binary tree. What is its time and space complexity, and why?
ANSWER
``java
int height(TreeNode node) {
if (node == null) return -1;
return 1 + Math.max(height(node.left), height(node.right));
}
``
Time complexity: O(n) because each node is visited exactly once. Space complexity: O(h) where h is the height of the tree due to the call stack. In the worst case (skewed tree), h = n so O(n) stack space. In a balanced tree, h = log n.
Q03 of 04SENIOR
A balanced binary tree has n nodes. What is the relationship between its height and n? What happens to height in the worst case (skewed tree) and why?
ANSWER
For a balanced tree, height ≈ log₂(n). This is because each level can hold at most twice as many nodes as the previous. For n nodes, the minimum height is floor(log₂(n)). In the worst case (skewed tree), height = n - 1 because every node has only one child, creating a linear chain. This is why balancing algorithms like AVL and Red-Black maintain O(log n) height.
Q04 of 04SENIOR
Given a binary tree, implement an iterative method to find its maximum depth (height) without recursion.
ANSWER
``java
int maxDepth(TreeNode root) {
if (root == null) return -1;
Stack<Pair<TreeNode, Integer>> stack = new Stack<>();
stack.push(new Pair<>(root, 0));
int maxDepth = -1;
while (!stack.isEmpty()) {
Pair<TreeNode, Integer> pair = stack.pop();
TreeNode node = pair.getKey();
int depth = pair.getValue();
maxDepth = Math.max(maxDepth, depth);
if (node.left != null) stack.push(new Pair<>(node.left, depth + 1));
if (node.right != null) stack.push(new Pair<>(node.right, depth + 1));
}
return maxDepth;
}
``
We use an explicit stack to simulate recursion. Each stack entry holds a node and its current depth. We track the maximum depth encountered. This avoids stack overflow on deep trees.
01
What is the difference between the height and depth of a node in a binary tree? Can you give an example using a tree you draw on the whiteboard?
JUNIOR
02
Write a recursive function to find the height of a binary tree. What is its time and space complexity, and why?
SENIOR
03
A balanced binary tree has n nodes. What is the relationship between its height and n? What happens to height in the worst case (skewed tree) and why?
SENIOR
04
Given a binary tree, implement an iterative method to find its maximum depth (height) without recursion.
SENIOR
FAQ · 5 QUESTIONS
Frequently Asked Questions
01
What is the height of a binary tree with only one node?
It's 0. A single node is both the root and a leaf. There are no edges below it, so the longest path to a leaf has 0 edges. This is why we define null nodes as height -1: height(single node) = 1 + max(-1, -1) = 0.
Was this helpful?
02
Is the height of a tree the same as the number of levels?
Almost — but off by one. A tree with height 3 has 4 levels (levels 0, 1, 2, and 3). Height counts edges; levels count nodes on each tier. So number of levels = height + 1. This off-by-one trips people up constantly, so keep it in mind.
Was this helpful?
03
What is the depth of a tree versus the height of a tree?
Strictly speaking, 'depth of a tree' isn't a standard term — depth applies to individual nodes. The correct term for how tall the whole tree is is the 'height of the tree', which equals the height of the root node. Some textbooks loosely use depth of tree to mean the same as height, so if you see it in the wild, they almost certainly mean height.
Was this helpful?
04
What is the minimum height of a binary tree with n nodes?
Floor(log2(n)) — achieved when the tree is a complete binary tree (each level filled left to right). For n=7 nodes the minimum height is 2 (a perfect binary tree). For n=8 the minimum height is 3.
Was this helpful?
05
How do you check if a binary tree is balanced (height-balanced)?
A tree is height-balanced if for every node, the heights of its left and right subtrees differ by at most 1. Check recursively: compute the height of each subtree; if the difference exceeds 1, return 'unbalanced'. To avoid O(n^2), combine the balance check with height computation in one DFS pass — return -1 as a sentinel for 'unbalanced'.