"Day 33: Balanced Binary Tree Challenge on LeetCode"

✅ Day 33 of #100DaysOfCode Challenge 📘 LeetCode Problem 110: Balanced Binary Tree 🧩 Problem Statement:  Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than 1. Example: Input: root = [3,9,20,null,null,15,7] Output: true Explanation:  Both left and right subtrees of every node differ in height by at most 1. 💡 Approach (Simple & Efficient): Use a recursive function to calculate the height of each subtree. If any subtree is unbalanced, return -1. Otherwise, return the height of the tree. If the final result is -1 → tree is not balanced. 💻 Java Code: class Solution {   public boolean isBalanced(TreeNode root) {     return checkHeight(root) != -1;   }   private int checkHeight(TreeNode node) {     if (node == null) return 0;     int leftHeight = checkHeight(node.left);     if (leftHeight == -1) return -1;     int rightHeight = checkHeight(node.right);     if (rightHeight == -1) return -1;     if (Math.abs(leftHeight - rightHeight) > 1) return -1;     return 1 + Math.max(leftHeight, rightHeight);   } } ⚙ Complexity: ⏱ Time: O(n) → Each node visited once 💾 Space: O(h) → Recursion stack (h = tree height) 🌱 Another step towards mastering Binary Trees!  #Day33 #100DaysOfCode #LeetCode #Java #DSA #BinaryTree #BalancedTree #Recursion #CodingChallenge

  • text

To view or add a comment, sign in

Explore content categories