Solved Binary Tree Diameter Problem in C++ with Recursion

🚀 Day 93 of My #100DaysOfCode Challenge! Today, I explored one of the most fundamental and elegant problems in Binary Trees — the Diameter of a Binary Tree 🌳 using C++. The goal of this problem is to find the longest path between any two nodes in a binary tree. This path may or may not pass through the root. To solve it efficiently, I used recursion and the concept of tree height. 💡 What I Learned: 🔹 Height Function: The height of a node is 1 + max(height(left), height(right)). I built a recursive function height(TreeNode* root) that returns the height of any subtree. 🔹 Diameter Function: For each node, I calculated three possible diameters: Diameter of the left subtree Diameter of the right subtree Diameter passing through the current node (left height + right height) The maximum of these three gives the current diameter. 🔹 Key Insight: This approach uses recursion twice (once for height and once for diameter), which makes it O(N²) — a good starting point for understanding the logic before optimizing it to O(N) with a single traversal. 🧠 Concepts Strengthened: Recursive Tree Traversal Depth & Height calculation Problem decomposition using subproblems Understanding tree structure visualization 🌱 Slowly mastering trees — one recursive function at a time! Next step: Optimize the diameter function for O(N) time complexity using a single DFS call. #Day93 #100DaysOfCode #CPlusPlus #DSA #BinaryTree #Recursion #ProblemSolving #CodingJourney #LeetCode

  • text

To view or add a comment, sign in

Explore content categories