LeetCode 236: Lowest Common Ancestor of a Binary Tree

Day 38 of #75DaysofLeetCode 🚀 Cracked LeetCode 236 – Lowest Common Ancestor of a Binary Tree! Understanding trees becomes powerful when you master problems like LCA 🌳 💡 Problem Insight: Given a binary tree, find the lowest node that has both p and q as descendants. 🔍 Key Idea: Instead of storing paths, we can solve this using a simple recursive DFS: If current node is null, p, or q → return it Search left and right subtree If both sides return non-null → 🎯 current node is the LCA Otherwise → return the non-null side ⚡ Why this works? Because the first node where both p and q appear in different subtrees is their lowest common ancestor. ⏱ Complexity: Time: O(N) Space: O(H) 📌 Takeaway: You don’t always need extra data structures—smart recursion can simplify complex tree problems! #LeetCode #DataStructures #Java #CodingInterview #BinaryTree #DFS #TechJourney

  • text

To view or add a comment, sign in

Explore content categories