Mohan Lal’s Post

Solved LeetCode 110 – Balanced Binary Tree 🌳 Most people start with a brute-force approach (recomputing heights again and again), which leads to O(n²) in worst cases. Instead, I focused on an optimized bottom-up DFS (post-order traversal). 💡 Key idea: Each node returns its height if balanced Returns -1 as a sentinel if unbalanced Propagates early to avoid unnecessary computation class Solution { public boolean isBalanced(TreeNode root) { return checkHeight(root) != -1; } int checkHeight(TreeNode node){ if (node == null) return 0; int left = checkHeight(node.left); int right = checkHeight(node.right); if (left == -1 || right == -1) return -1; if (Math.abs(left - right) > 1) return -1; return Math.max(left, right) + 1; } } 🚀 Complexity: Time: O(n) Space: O(h) (recursion stack) 📌 What I learned: Combining multiple computations (height + balance) into a single traversal Using sentinel values to simplify recursion Thinking in bottom-up patterns for tree problems This pattern is widely useful in tree-based problems and even shows up in backend systems where hierarchical data needs validation. #Java #DataStructures #Algorithms #LeetCode #CodingInterview #BackendDevelopment

  • text

To view or add a comment, sign in

Explore content categories