Tensorum
YouTubeसीखना शुरू करें
LeetCode 110 · DFS Basics

Balanced Binary Tree

LeetCode 110 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Height DFS that returns −1 on imbalance.

आसानTreeDepth-First SearchBinary Tree

मैंने 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²).