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²).