Tensorum
YouTubeশেখা শুরু করুন
LeetCode 110 · DFS Basics

Balanced Binary Tree

LeetCode 110 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Height DFS that returns −1 on imbalance.

সহজTreeDepth-First SearchBinary Tree
LeetCode-এ খুলুন ↗

আমি Balanced Binary Tree (LeetCode 110) এভাবে সমাধান করেছি — DFS Basics প্যাটার্নের একটি সহজ প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।

নিচের বিবরণ ইংরেজিতে।

Intuition

Compute heights bottom-up, and use −1 as a signal that a subtree is already unbalanced. That way each node is visited once and an imbalance short-circuits everything above it.

Approach

  1. 1

    Empty → height 0.

  2. 2

    Get the left height; −1 → propagate.

  3. 3

    Get the right height; −1 → propagate.

  4. 4

    Difference > 1 → −1; else 1 + max.

আমি কীভাবে সমাধান করেছি

Height with sentinelPythonO(n) time · O(h) space
class Solution:
    def isBalanced(self, root):
        def dfs(node):
            if node is None:
                return 0
            lh = dfs(node.left)
            if lh == -1:
                return -1
            rh = dfs(node.right)
            if rh == -1:
                return -1
            if abs(lh - rh) > 1:
                return -1
            return 1 + max(lh, rh)
        return dfs(root) != -1
স্টেপ-থ্রু লোড হচ্ছে…

Balanced Binary Tree — সাধারণ প্রশ্ন

Balanced Binary Tree-এর পেছনে intuition কী?

Compute heights bottom-up, and use −1 as a signal that a subtree is already unbalanced. That way each node is visited once and an imbalance short-circuits everything above it.

Balanced Binary Tree (LeetCode 110) কীভাবে সমাধান করবেন?

1. Empty → height 0. 2. Get the left height; −1 → propagate. 3. Get the right height; −1 → propagate. 4. Difference > 1 → −1; else 1 + max.

Balanced Binary Tree-এর time আর space complexity কত?

Time: O(n)। Space: O(h)। (Accepted approach: Height with sentinel।)

Balanced Binary Tree-এ সাধারণ ভুলগুলো কী?

Computing height separately at every node is O(n²).