diff --git a/src/main/java/com/thealgorithms/datastructures/trees/DiameterOfBinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/DiameterOfBinaryTree.java new file mode 100644 index 000000000000..36f09c79f94a --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/trees/DiameterOfBinaryTree.java @@ -0,0 +1,40 @@ +package com.thealgorithms.datastructures.trees; + +/** + * Computes the diameter of a binary tree — the length of the longest path + * between any two nodes (the path may or may not pass through the root). + * + *
Example: + *
+ * 1 + * / \ + * 2 3 + * / \ + * 4 5 + * Diameter: 3 (path: 4 -> 2 -> 1 -> 3 or 5 -> 2 -> 1 -> 3) + *+ * + *
Time complexity: O(n), Space complexity: O(h) where h is tree height. + * + * @see LeetCode #543 + */ +public final class DiameterOfBinaryTree { + private DiameterOfBinaryTree() { + } + + public static int diameterOfBinaryTree(BinaryTree.Node root) { + int[] maxDiameter = {0}; + depth(root, maxDiameter); + return maxDiameter[0]; + } + + private static int depth(BinaryTree.Node node, int[] maxDiameter) { + if (node == null) { + return 0; + } + int leftDepth = depth(node.left, maxDiameter); + int rightDepth = depth(node.right, maxDiameter); + maxDiameter[0] = Math.max(maxDiameter[0], leftDepth + rightDepth); + return 1 + Math.max(leftDepth, rightDepth); + } +} diff --git a/src/test/java/com/thealgorithms/datastructures/trees/DiameterOfBinaryTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/DiameterOfBinaryTreeTest.java new file mode 100644 index 000000000000..d5cdfa1eee16 --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/trees/DiameterOfBinaryTreeTest.java @@ -0,0 +1,47 @@ +package com.thealgorithms.datastructures.trees; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class DiameterOfBinaryTreeTest { + + @Test + public void testNullRoot() { + assertEquals(0, DiameterOfBinaryTree.diameterOfBinaryTree(null)); + } + + @Test + public void testSingleNode() { + BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1}); + assertEquals(0, DiameterOfBinaryTree.diameterOfBinaryTree(root)); + } + + /* + 1 + / \ + 2 3 + / \ + 4 5 + Diameter: 3 + */ + @Test + public void testDiameterThroughRoot() { + BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5}); + assertEquals(3, DiameterOfBinaryTree.diameterOfBinaryTree(root)); + } + + /* + 1 + / + 2 + / + 3 + Diameter: 2 + */ + @Test + public void testLinearTree() { + BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, null, 3}); + assertEquals(2, DiameterOfBinaryTree.diameterOfBinaryTree(root)); + } +}