Skip to content

Commit

Permalink
feature: balanced binary tree revisit
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Nov 15, 2023
1 parent de76f49 commit 2257eb5
Showing 1 changed file with 5 additions and 13 deletions.
18 changes: 5 additions & 13 deletions trees/BalancedBinaryTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,11 @@
def is_balanced(self, root: Optional[TreeNode]) -> bool:
def dfs(node):
if not node:
return True, -1
return 0, True

l_balanced, l_height = dfs(node.left)
if not l_balanced:
return False, 0
l_height, l_balanced = dfs(node.left)
r_height, r_balanced = dfs(node.right)

r_balanced, r_height = dfs(node.right)
if not r_balanced:
return False, 0
return max(l_height, r_height) + 1, l_balanced and r_balanced and abs(l_height - r_height) <= 1

return (
abs(l_height - r_height) < 2,
1 + max(l_height, r_height)
)

return dfs(root)[0]
return dfs(root)[1]

0 comments on commit 2257eb5

Please sign in to comment.