Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0df55b3

Browse files
Create balanced_binary_tree.py
1 parent 30fb11f commit 0df55b3

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎day-23/balanced_binary_tree.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Problem: Balanced Binary Tree
2+
# Link: https://leetcode.com/problems/balanced-binary-tree/description/
3+
# Tags: Tree, DFS, Recursion, Divide and Conquer
4+
# Approach: Use a post-order DFS that computes subtree heights and detects imbalance early.
5+
# For each node, obtain left and right heights; if either subtree is already
6+
# unbalanced or their height difference exceeds 1, propagate an unbalanced signal.
7+
# Otherwise return 1 + max(left_height, right_height). This short-circuits on the
8+
# first violation and visits each node once.
9+
# Time Complexity: O(n)
10+
# Space Complexity: O(h) where h is the tree height
11+
12+
13+
class Solution:
14+
def isBalanced(self, root):
15+
def dfs(node):
16+
if not node:
17+
return True, 0
18+
lb, lh = dfs(node.left)
19+
if not lb:
20+
return False, 0
21+
rb, rh = dfs(node.right)
22+
if not rb:
23+
return False, 0
24+
ok = abs(lh - rh) <= 1
25+
return ok, 1 + (lh if lh > rh else rh)
26+
27+
ok, _ = dfs(root)
28+
return ok

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /