Create bst_is_balanced.py

This commit is contained in:
marina 2023-08-03 15:55:38 -07:00 committed by GitHub
parent 177914c7be
commit 817cbb57a2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

21
trees/bst_is_balanced.py Normal file
View 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)