Calculating Binary Tree Diameter with DFS in Java

🌲 Day 38/75: Measuring the Diameter of a Binary Tree! Today’s LeetCode challenge was a step up in complexity: finding the Diameter of a Binary Tree. The diameter is the length of the longest path between any two nodes in a tree, which may or may not pass through the root. The Strategy: This problem is tricky because the longest path isn't always just the height of the left side plus the height of the right side at the root. It could be tucked away in one of the subtrees! I used a recursive Depth-First Search (DFS) that performs two tasks at once: Calculates Height: It returns the height of the current subtree to its parent. Updates Diameter: It calculates the path passing through the current node (leftHeight + rightHeight) and updates a global diameter variable if this path is the longest found so far. Performance: ✅ Runtime: 1 ms ✅ Complexity: $O(n)$ Time | $O(h)$ Space It’s a great example of how to extract multiple pieces of information from a single recursive pass. One more day closer to the 40-day mark! 🚀 #LeetCode #75DaysOfCode #Java #BinaryTree #Recursion #Algorithms #DataStructures #TechJourney

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories