Balanced Binary Tree
LeetCode 110 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Height DFS that returns −1 on imbalance.
నేను 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
Empty → height 0.
- 2
Get the left height; −1 → propagate.
- 3
Get the right height; −1 → propagate.
- 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) != -1Balanced 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²).