diff --git a/algorithms-and-data-structures/src/main/java/com/xtenzq/tree/BinaryTree.java b/algorithms-and-data-structures/src/main/java/com/xtenzq/tree/BinaryTree.java new file mode 100644 index 0000000..ec7af4e --- /dev/null +++ b/algorithms-and-data-structures/src/main/java/com/xtenzq/tree/BinaryTree.java @@ -0,0 +1,29 @@ +package com.xtenzq.tree; + +import com.xtenzq.tree.utils.TreeNode; + +public class BinaryTree { + + /** + * Computes the maximum depth of a binary tree. + * + * @param root the root node of the binary tree + * @return the maximum depth of the binary tree + * @implNote The time complexity of this method is {@code O(n)}, where n is the number of nodes in the binary tree. + * This is because the method visits each node exactly once. + *

+ * The space complexity of this method is {@code O(h)}, where {@code h} is the height of the binary tree. + * This is due to the recursion stack. In the worst case, the height of the tree can be {@code n} (in case of a completely skewed tree). + * Therefore, the space complexity can be considered {@code O(h)} in the worst case and {@code O(log h)} in the best case (for a balanced tree). + * @see 104. Maximum Depth of Binary Tree + */ + public static int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + + int left = maxDepth(root.left); + int right = maxDepth(root.right); + return Math.max(left, right) + 1; + } +} diff --git a/algorithms-and-data-structures/src/test/java/com/xtenzq/tree/BinaryTreeTest.java b/algorithms-and-data-structures/src/test/java/com/xtenzq/tree/BinaryTreeTest.java new file mode 100644 index 0000000..5013240 --- /dev/null +++ b/algorithms-and-data-structures/src/test/java/com/xtenzq/tree/BinaryTreeTest.java @@ -0,0 +1,20 @@ +package com.xtenzq.tree; + +import org.junit.jupiter.api.Test; + +import static com.xtenzq.tree.BinaryTree.maxDepth; +import static com.xtenzq.tree.utils.TreeNode.buildTree; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BinaryTreeTest { + + @Test + void maxDepth_case1() { + assertEquals(3, maxDepth(buildTree(3, 9, 20, null, null, 15, 7))); + } + + @Test + void maxDepth_case2() { + assertEquals(2, maxDepth(buildTree(1, null, 2))); + } +} \ No newline at end of file