mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 04:36:08 -04:00
Create bst_is_balanced.py
This commit is contained in:
parent
177914c7be
commit
817cbb57a2
21
trees/bst_is_balanced.py
Normal file
21
trees/bst_is_balanced.py
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# author: bt3gl
|
||||||
|
|
||||||
|
|
||||||
|
def height(root):
|
||||||
|
|
||||||
|
if not root:
|
||||||
|
return -1
|
||||||
|
|
||||||
|
return 1 + max(height(root.left), height(root.right))
|
||||||
|
|
||||||
|
|
||||||
|
def is_balanced(root):
|
||||||
|
|
||||||
|
if not root:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return abs(height(root.left) - height(root.right)) < 2 and \
|
||||||
|
is_balanced(root.left) and is_balanced(root.right)
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user