Skip to content

Commit 8ce83b0

Browse files
feat: add max-depth-binary-tree algorithm with tests
1 parent 1e59594 commit 8ce83b0

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.thealgorithms.datastructures.trees;
2+
3+
/**
4+
* Finds the maximum depth (height) of a binary tree — the number of nodes
5+
* along the longest path from the root down to the farthest leaf node.
6+
*
7+
* <p>Example:
8+
* <pre>
9+
* 3
10+
* / \
11+
* 9 20
12+
* / \
13+
* 15 7
14+
* Maximum depth: 3
15+
* </pre>
16+
*
17+
* <p>Time complexity: O(n), Space complexity: O(h) where h is tree height.
18+
*
19+
* @see <a href="https://leetcode.com/problems/maximum-depth-of-binary-tree/">LeetCode #104</a>
20+
*/
21+
public final class MaximumDepthOfBinaryTree {
22+
private MaximumDepthOfBinaryTree() {
23+
}
24+
25+
public static int maxDepth(BinaryTree.Node root) {
26+
if (root == null) {
27+
return 0;
28+
}
29+
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
30+
}
31+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.thealgorithms.datastructures.trees;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class MaximumDepthOfBinaryTreeTest {
8+
9+
@Test
10+
public void testNullRoot() {
11+
assertEquals(0, MaximumDepthOfBinaryTree.maxDepth(null));
12+
}
13+
14+
@Test
15+
public void testSingleNode() {
16+
BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1});
17+
assertEquals(1, MaximumDepthOfBinaryTree.maxDepth(root));
18+
}
19+
20+
/*
21+
3
22+
/ \
23+
9 20
24+
/ \
25+
15 7
26+
Max depth: 3
27+
*/
28+
@Test
29+
public void testMaxDepth() {
30+
BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {3, 9, 20, null, null, 15, 7});
31+
assertEquals(3, MaximumDepthOfBinaryTree.maxDepth(root));
32+
}
33+
34+
/*
35+
1
36+
/
37+
2
38+
Max depth: 2
39+
*/
40+
@Test
41+
public void testLeftOnlyTree() {
42+
BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2});
43+
assertEquals(2, MaximumDepthOfBinaryTree.maxDepth(root));
44+
}
45+
}

0 commit comments

Comments
 (0)