FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/tree/is_balanced.py at master · ivan1911/algorithms-python · GitHub
ivan1911
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
tree
/
is_balanced.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
37 lines (30 loc) · 833 Bytes
Breadcrumbs
algorithms-python
/
algorithms
/
tree
/
is_balanced.py
Copy path
File metadata and controls
37 lines (30 loc) · 833 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
def
is_balanced
(
root
):
return
__is_balanced_recursive
(
root
)
def
__is_balanced_recursive
(
root
):
"""
O(N) solution
"""
return
-
1
!=
__get_depth
(
root
)
def
__get_depth
(
root
):
"""
return 0 if unbalanced else depth + 1
"""
if
root
is
None
:
return
0
left
=
__get_depth
(
root
.
left
)
right
=
__get_depth
(
root
.
right
)
if
abs
(
left
-
right
)
>
1
or
-
1
in
[
left
,
right
]:
return
-
1
return
1
+
max
(
left
,
right
)
# def is_balanced(root):
# """
# O(N^2) solution
# """
# left = max_height(root.left)
# right = max_height(root.right)
# return abs(left-right) <= 1 and is_balanced(root.left) and
# is_balanced(root.right)
# def max_height(root):
# if root is None:
# return 0
# return max(max_height(root.left), max_height(root.right)) + 1
Back
|
FazBrowse Home
|
New Git URL