leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

balanced-binary-tree.py (400B)


      1 class Solution:
      2     def isBalanced(self, root: Optional[TreeNode]) -> bool:
      3         return dfs(root) != -1
      4 
      5 
      6 # return depth of tree
      7 def dfs(root):
      8 
      9     if root is None:
     10         return 0
     11 
     12     left_depth = dfs(root.left)
     13     right_depth = dfs(root.right)
     14 
     15     if abs(right_depth - left_depth) > 1 or left_depth == -1 or right_depth == -1:
     16         return -1
     17 
     18     return max(left_depth, right_depth) + 1