diff --git a/src/main/java/com/thealgorithms/datastructures/trees/MaximumDepthOfBinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/MaximumDepthOfBinaryTree.java new file mode 100644 index 000000000000..653cec2845d0 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/trees/MaximumDepthOfBinaryTree.java @@ -0,0 +1,31 @@ +package com.thealgorithms.datastructures.trees; + +/** + * Finds the maximum depth (height) of a binary tree — the number of nodes + * along the longest path from the root down to the farthest leaf node. + * + *

Example: + *

+ *      3
+ *     / \
+ *    9  20
+ *       / \
+ *      15   7
+ * Maximum depth: 3
+ * 
+ * + *

Time complexity: O(n), Space complexity: O(h) where h is tree height. + * + * @see LeetCode #104 + */ +public final class MaximumDepthOfBinaryTree { + private MaximumDepthOfBinaryTree() { + } + + public static int maxDepth(BinaryTree.Node root) { + if (root == null) { + return 0; + } + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + } +} diff --git a/src/test/java/com/thealgorithms/datastructures/trees/MaximumDepthOfBinaryTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/MaximumDepthOfBinaryTreeTest.java new file mode 100644 index 000000000000..328373001d2f --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/trees/MaximumDepthOfBinaryTreeTest.java @@ -0,0 +1,45 @@ +package com.thealgorithms.datastructures.trees; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class MaximumDepthOfBinaryTreeTest { + + @Test + public void testNullRoot() { + assertEquals(0, MaximumDepthOfBinaryTree.maxDepth(null)); + } + + @Test + public void testSingleNode() { + BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1}); + assertEquals(1, MaximumDepthOfBinaryTree.maxDepth(root)); + } + + /* + 3 + / \ + 9 20 + / \ + 15 7 + Max depth: 3 + */ + @Test + public void testMaxDepth() { + BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {3, 9, 20, null, null, 15, 7}); + assertEquals(3, MaximumDepthOfBinaryTree.maxDepth(root)); + } + + /* + 1 + / + 2 + Max depth: 2 + */ + @Test + public void testLeftOnlyTree() { + BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2}); + assertEquals(2, MaximumDepthOfBinaryTree.maxDepth(root)); + } +}