We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 28ede22 commit a3cd69eCopy full SHA for a3cd69e
Trees-and-Graphs/check-balanced.py
@@ -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