Check if a given binary tree is balanced. A balanced binary tree is one in which the depths of every node’s left and right subtree differ by at most 1.
Examples
5
/ \
3 8
/ \ \
1 4 11
is balanced binary tree,
5
/
3
/ \
1 4
is not balanced binary tree.
class Solution(object):
def isBalanced(self, root):
if not root:
return True
return self.helper(root) != -1
def helper(self,root):
if not root:
return 0
left = self.helper(root.left)
right = self.helper(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left,right) + 1