Skip to main content

110. Balanced Binary Tree

https://leetcode.com/problems/balanced-binary-tree/

Python

  • 雙層的recursion...
class Solution:
def get_depth(self, node):
if not node:
return -1
return 1 + max(self.get_depth(node.left), self.get_depth(node.right))

def check(self, node):
if not node:
return True
return abs(self.get_depth(node.left) - self.get_depth(node.right)) <= 1 \
and self.check(node.left) \
and self.check(node.right)

def isBalanced(self, root: Optional[TreeNode]) -> bool:
return self.check(root)