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