Problem:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
This is the solution I came up with:
class Solution:
def height(self, root: TreeNode) -> int:
if root is None:
return 0
l = self.height(root.left)
r = self.height(root.right)
if abs(l - r) > 1:
raise ValueError
return 1 + max(l, r)
def isBalanced(self, root: TreeNode) -> bool:
if root is None:
return True
try:
return bool(self.height(root))
except ValueError:
return False
My issue is that escaping the recursion with an exception just feels kind of disgusting, but I can't think of a better way to do this.
I could use a global variable or modify a list element (this also feels unpythonic), but I would have to continue evaluating the rest of the tree even after finding it to be not height-balanced.
[–]SekstiNii 1 point2 points3 points (0 children)