Skip to content

Commit a3cd69e

Browse files
committed
Check Balanced
1 parent 28ede22 commit a3cd69e

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

Trees-and-Graphs/check-balanced.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""
2+
Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined
3+
to be a tree such that the heights of the two subtrees of any node never differ by more than one.
4+
"""
5+
class Solution(object):
6+
def isBalanced(self, root):
7+
def check(root):
8+
if root is None:
9+
return 0
10+
left = check(root.left)
11+
right = check(root.right)
12+
if left == -1 or right == -1 or abs(left - right) > 1:
13+
return -1
14+
return 1 + max(left, right)
15+
return check(root) != -1

0 commit comments

Comments
 (0)