-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path110.balanced-binary-tree.py
66 lines (45 loc) · 1.43 KB
/
110.balanced-binary-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from lc import *
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def f(x):
if not x:
return 0
l = f(x.left)
r = f(x.right)
if l==None or r==None or abs(l-r)>1:
return None
return 1+max(l,r)
return f(root) if root else True
class Solution:
def isBalanced(self, root: TreeNode):
return not root or abs((f:=lambda r:1+max(f(r.left),f(r.right)) if r else 0)(root.left)-f(root.right))<2 and self.isBalanced(root.left) and self.isBalanced(root.right)
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
return not root or (f:=lambda x:(None if (l:=f(x.left))==None or (r:=f(x.right))==None or abs(l-r)>1 else 1+max(l,r)) if x else 0)(root)
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
return (f:=lambda x:(((l:=f(x.left))<0 or (r:=f(x.right))<0 or abs(l-r)>1) and -1) or 1+max(l,r) if x else 0)(root)>=0
test('''
110. Balanced Binary Tree
Easy
7631
402
Add to List
Share
Given a binary tree, determine if it is height-balanced.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3:
Input: root = []
Output: true
Example 4:
Input: root = [3,9,20,null,null,15,7]
Output: true
Constraints:
The number of nodes in the tree is in the range [0, 5000].
-10^4 <= Node.val <= 10^4
''')