How to find the diameter of a binary tree using recursion

🚀 Day 112 of #LeetCode Challenge! Problem: Diameter of Binary Tree 💡 My Approach: The diameter of a binary tree is the longest path between any two nodes (may or may not pass through the root). The trick is to calculate the height of each subtree while keeping track of the maximum left + right path encountered. Use a helper function height() that: Recursively computes left and right subtree heights. Updates the global diameter as the maximum sum of left and right heights. ✨ Example: Input: [1,2,3,4,5] Output: 3 Explanation: The longest path is [4,2,1,3] or [5,2,1,3] ⏱ Time Complexity: O(N) — visit every node once 💾 Space Complexity: O(H) — recursive stack (H = height of tree) 🌱 Key Insight: At each node, the longest path through it is leftHeight + rightHeight. The overall diameter is the maximum of all such paths. 👨💻 GitHub Link: https://lnkd.in/dvUDMZUC #LeetCode #BinaryTree #Recursion #TreeTraversal #DSA #CodingChallenge #C++ #Day112

  • text

To view or add a comment, sign in

Explore content categories