Solution
# Definition for a binary tree node.
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def dfs(node) -> int:
if not node:
return 0
left_height = dfs(node.left)
right_height = dfs(node.right)
if left_height == -1 or right_height == -1 \
or abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1
return dfs(root) >= 0
Leave a comment