[LeetCode]110. Balanced Binary Tree
110. Balanced Binary Tree
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def getpath(node):
if not node:
return 0
return max(getpath(node.left), getpath(node.right)) + 1
if not root:
return True
left = getpath(root.left)
right = getpath(root.right)
return 0 <= abs(left - right) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
class Solution(object):
def checkBalanced(self, root):
if root == None:
return True, -1
(balance_left, depth_left) = self.checkBalanced(root.left)
if balance_left == False:
return False, None
(balance_right, depth_right) = self.checkBalanced(root.right)
if balance_right == False:
return False, None
if abs(depth_left-depth_right) > 1:
return False, None
else:
return True, max(depth_left,depth_right)+1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
(balance, depth) = self.checkBalanced(root)
return balance
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法

浙公网安备 33010602011771号